Examveda

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;
}

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 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.

This Question Belongs to C Program >> Structure And Union

Join The Discussion

Comments (1)

  1. Shalini Shalini
    Shalini Shalini:
    2 years ago

    How

Related Questions on Structure and Union