Search code examples
cruntime-errorunions

Runtime error when printing string using union. It doesn't print string value but does print integer value


the print statementthe output I get

    for(i = 0; i<n; i++) //printing
    {printf("Name: %s\nAddress: %s\nOccupation: %s\nAge: %d", p[i].name, p[i].add, p[i].occ, p[i].age);}

Solution

  • If p[i] is a union, then it can hold only one of its members. However, in your print:

    printf("Name: %s\nAddress: %s\nOccupation: %s\nAge: %d", p[i].name, p[i].add, p[i].occ, p[i].age);
    

    you seem to think it holds all of the values. For that you don't need a union but a struct.