?
What will be the output of the following C code?
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;
}
Answer & Solution
Correct Answer:
Option
B
In this code, the variable
q 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.
Join the Discussion
Login to post a comment or share your explanation.
Login