Here are some important struct and union based interview questions for experienced. In C  language struct and union provides a way to pack different data types under a single tag name. The fundamental difference between struct and union is , the data members of struct use different memory locations while data members of union use  same memory location. So we can use only one data members of union at time. Let us see some basic example.

struct example in c

#include<stdio.h>

struct foo {
   int id;
   char *name;
};

struct foo f={123,"wikistack"};

int main()
{
  printf("id=%d name= %s\n",f.id, f.name);
  return 0;
}

Compile and Run

#gcc sample.c -o sample

#./sample

id=123 name= wikistack

Union example in c

#include<stdio.h>

union foo {
   int id;
   char *name;
};

int main()
{
  union foo f;
  f.id = 123;
  f.name = "wikistack";
  printf("id=%d name = %s\n",f.id, f.name);
  return 0;
}

Compile and Run

#gcc sample.c -o sample

#./sample

id=4195828 name = wikistack

Note:  Look at the output , the data member of union id has been assigned value 123, while the output is 4195828. This happens because union uses same memory location for its data members.  In our example as soon as the statement f.name = “wikistack” has been executed the value of data member id affected.

struct and union based interview questions for experienced

Q (1) what is problem with below code?

#include<stdio.h>

struct foo {
   int id;
   struct foo f;
};

int main()
{
  return 0;
}

A structure or union cannot contain a member of its own type however a pointer of same type can be a member of union or struct. The declaration of same type is not allowed because in this case compiler would not decide size of  structure or union.

Q (2) what would be output of below code?

#include<stdio.h>

struct foo {
   int a;
   char c[5];
};
struct foo f;
int main()
{
  printf("size of foo is %d\n",sizeof(f));
  return 0;
}

output:

size of foo is 12

Note: Compiler insert some padding bits inside struct for the structure members to “natural” address boundaries.

Q (3) how can you remove padding inside  struct?

#include<stdio.h>

struct  __attribute__((__packed__)) foo {
   int a;
   char c[5];
};
struct foo f;
int main()
{
  printf("size of foo is %d\n",sizeof(f));
  return 0;
}

output: size of foo is 9

Packing __attribute__((__packed__))  , prevents compiler from doing padding

Q (4) what is practical use of struct inside union?

Q (5) what is practical use of union inside struct?

Q(6) why the below code is compiling successfully even though semicolon is missing?

#include<stdio.h>

typedef struct map
{
   int id;
   char *name /* no semicolon here */
}map;

int main()
{
    return 0;
}

 

Ref:

https://stackoverflow.com/questions/346536/difference-between-a-structure-and-a-union-in-c

difference between struct and union




Related Contents to follow