What will be the output of the following C code?
#include <stdio.h>
struct p
{
char *name;
struct p *next;
};
struct p *ptrary[10];
int main()
{
struct p p, q;
p.name = "xyz";
p.next = NULL;
ptrary[0] = &p;
strcpy(q.name, p.name);
ptrary[1] = &q;
printf("%s\n", ptrary[1]->name);
return 0;
}
#include <stdio.h>
struct p
{
char *name;
struct p *next;
};
struct p *ptrary[10];
int main()
{
struct p p, q;
p.name = "xyz";
p.next = NULL;
ptrary[0] = &p;
strcpy(q.name, p.name);
ptrary[1] = &q;
printf("%s\n", ptrary[1]->name);
return 0;
}
A. Compile time error
B. Segmentation fault/code crash
C. Depends on the compiler
D. xyz
Answer: Option B
Solution (By Examveda Team)
In this code, the variableq
is declared but not initialized. When you try to use strcpy
function to copy the value of p.name
to q.name
, you are accessing memory that has not been allocated for q.name
, which leads to undefined behavior. This undefined behavior could result in a segmentation fault or a code crash. Therefore, the correct answer is Option B: Segmentation fault/code crash.
How