Structures in C

1. Consider the following C declaration
struct {
    short s [5]
    union {
         float y;
         long z;
    }u;
} t;
Assume that objects of the type short, float and long occupy 2 bytes, 4 bytes and 8 bytes, respectively. The memory requirement for variable t, ignoring alignment considerations, is -------

18

The reason is, the size of a union object is size of its largest element. So in this case size of u will be equal to size of long - 8 bytes. Size of s array will be equal to size of array X size of one element = 5X2 = 10 bytes. So total size of structure is 18 bytes.

2. What will be output when you will execute following c code?
#include<stdio.h>
enum Alpha{
      X,
      Y=5,
      Z
}p=10;
int main(){
    enum Alpha a,b;
    a= X;
    b= Z;
    printf("%d",a+b-p);
    return 0;
}

-4

Enumerated types are integer constants you define in a program. The constant inside enum without initialization will have value of 0 if it is first tag. If not, it will have a value 1+preceding value. So X in the enum Alpha is equal to 0. So a is 0, b is 6 and p is 10.

3. Write output of the following program
#include<stdio.h>
int main()
{
    struct st
    {
        char name[] = "hello world";
        int num = 200;
    };
    struct st *ptr;
    printf("%d ", ptr->num);
    printf("%s", ptr->name);
    return 0;
}
Compilation error

It is invalid to initialize members of a structure inside its declaration. So char name[] = "Hello world" and int num = 200 are both syntactically wrong.

4. Assume that size of an integer is 32 bit. What is the output of following program?
#include<stdio.h>
struct st
{
    int x;
    static int y;
};
int main()
{
    printf("%d", sizeof(struct st));
    return 0;
}

Compilation error

The structure member can not be static. So static int y in the structure definition is wrong.

5.
struct node
{
   int i;
   float j;
};
struct node *s[10];
What is the type of s in the above code?

s is an array of 10 pointers to structure node.

6. What will be output of following c code?
int  main()
{
  struct bitfield
  {
     signed int a:3;
     unsigned int b:13;
     unsigned int c:1;
  };
  struct bitfield bit1={2,14,1};
  printf("%d",sizeof(bit1));
}

4

You would expect the size of bitfield structure to be 17 bits or 2 bytes. But because of structure padding, the size of bit1 is 1 word = 4 bytes.

7. What is the output of following C code?
int main()
{
   struct emp
   {
     char name[20];
     int age;
     float sal;
   };
   struct emp e ={"Tiger"}
   printf("%d %f",e.age,e.sal);
}
0 0.00000

If a structure is partially initialized, the initialized members are set to 0.

8. What is the output of this C code?
   #include <stdio.h>
   struct student
   {
       char *name;
   };
   struct student s[2], r[2];
   int  main()
   {
       s[0].name = "alan";
       s[1] = s[0];
       r = s;
       printf("%s%s", r[0].name, r[1].name);
   }

Compilation Error

The line r = s; gives a compilation error. Because we can't assign one array to another.

Also in the line s[0].name = "alan" gives a run time error, because we have not allocated memory to the pointer s[0].name.

9.
struct p
{
  int a;
  char b;
};
int main()
{
    struct p p1[] = {1, 92, 3, 94, 5, 96};
    struct p *ptr1 = p1;
}
What are p1 and ptr in the above program?

p1 is an array of 3 structures because it has totally 6 initial values.

ptr is a pointer to structure p and it points to p1[0]

10. What is the output of this C code?
   #include <stdio.h>
   struct student
   {
       char *c;
   };
   int  main()
   {
       struct student *s;
       s->c = "hello";
       printf("%s", s->c);
       }

Run time error. Segmentation fault

s is a pointer to structure. As it is not assigned to any structure, nor is any memory assigned to it, s is uninitialized pointer. Dereferencing such a pointer gives segmentation fault.

11. What is the output of the following program?
    struct q
    {
        int *x;
    };
    int main()
    {

        struct q *ptr;
        ptr = (struct q*)malloc(sizeof(struct q));
        *(ptr->x)=15;
        printf("%d",*(ptr->x));
        return 0;
      }

Run time error. Segmentation fault

x is a pointer member of structure. We can't dereference it before we assign a value to it.

12. What is a self referential stucture? Where is it used?

The structure with one of the members as pointer to same structure is called self referential structure.

struct node
   {
     int val;
    struct node *ptr;
   };

node is a self referential structure.

Self referential structures are building blocks of linked lists, trees, queues etc.

13. What is the output of the following program?
        #include <stdio.h>
        struct student
        {
            char *c;
            struct student *pointer;
        };
        int  main()
        {
            struct student s;
            struct student m;
            m.pointer = &s;
            (m.pointer)->c = "hey";
            printf("%s", s.c);
       }

hey

14.
#include <stdio.h>
union temp
   {
      int a;
      float b;
      char c;
    };
   union temp t1 ; t1.a=66;
What will be the value of temp.c after the above statements?

66

15. What's the difference between these two declarations?
	struct X1 { ... };
	typedef struct { ... } X2;

X1 is a structure tag. So a variable should be declared as

sturct X1 s1;

X2 is a type. Hence a structure using X2 can be defined without using struct keyword
X2 s1;
16. What is the size of
 struct a{int i;char c}
?
Why is it not 5 bytes?

Because of structure padding.

For faster access, each member of structure is aligned to word boundaries. This causes padding to be added in between members.

So after c of the structure 3 bytes are padded in a 32 bit machine. Hence size of struct is 8 bytes.

Avoidance of padding is implementation dependant. In gcc compiler it is done using

__attribute__((__packed__))

17. Can the members of union be initialized? If yes, how?

In ANSI 89 standard, only first member of union be initialized. But in C99 standard, different members can be initialized using a syntax such as

 union  aaa
 {
    int val;char ch;
 } ;
 union aaa temp =
  {
      .ch='P',.val=44
  };
 

And union will have the value which is assigned last.

18. Can we initialize members of struct in any order? If yes, how?

In C99 standard it is possible using initializer of the type

struct st s1 = {.val = 600,.ch='A'};

Here the member val is initialized to 600 and ch is initialized to 'A'.

19. What is the output of the following program?
#include<stdio.h>
enum m {a=6,b,c,d=3,e};
int main()
{
   enum m temp;
   temp = e;
   printf("%d",temp);
   return 0;
}

4

Unintialized tags in a enum will have values of one plus previous tag's value. As d is 3, e will be 4.

20. What are bit fields? How are they used?

A structure or a union may contain small fields which occupy less than one byte - n number of bits. Their usefulness is limited.

struct aa
{
  int a:3;
  unsigned int b:2;
  int m;
  };

Here bit field a is occupying 3 bits and b occupies 2 bits.

The only types allowed for bit fields are signed or unsigned ints.

You can not take address of a bit field.

21. What is the output of the program?
#include<stdio.h>
int main()
{
    enum color{red, green, blue};
    typedef enum color mycolor;
    mycolor m = red;
    printf("%d", m);
    return 0;
}

0

If a tag is not initialized in an enum, its value will be 0, if it is first field.

22. What will be the output of the program?
#include<stdio.h>
typedef struct error
 {
int warning, err, exception;
} ERROR;
int main()
{
    ERROR e;
    e.err=1;
    printf("%d\n", e.err);
    return 0;
}

1

23. In the following code snippet can we declare a new typedef named ptr even though struct employee has not been completely declared while using typedef?
typedef struct employee *ptr;
struct employee
{
    char name[20];
    int age;
    ptr next;
};

yes

24. Is the following code valid? If yes what are n and p?
typedef long no, *ptrtono;
no n;
ptrtono p;

n is long integer and p is a pointer to long integer.

25. Write a program to check if two rectangles overlap

#include<stdio.h>
struct rect
{
   int x,y;
   int len,wid;
};
int overlap(struct rect r1,struct rect r2);
int main()
{
    struct rect r1,r2;
    printf("Enter rectangle 1 x,y,length and width:");
    scanf("%d %d %d %d",&r1.x,&r1.y,&r1.len,&r1.wid);
    printf("Enter rectangle 2 x,y,length and width:");
    scanf("%d %d %d %d",&r2.x,&r2.y,&r2.len,&r2.wid);
    if(overlap(r1,r2))
       printf("The rectangles overlap");
    else
       printf("They don't overlap");
    return 0;
}

int overlap(struct rect r1,struct rect r2)
{
    if(r1.x>r2.x  && (r1.x-r2.x) < r1.len)
       return 1;
    if(r1.x==r2.x)
       return 1;
    if(r2.x >r1.x && (r2.x-r1.x) < r2.len)
      return 1;
    if(r1.y>r2.y  && (r1.y-r2.y) < r1.wid)
       return 1;
    if(r1.y==r2.y)
       return 1;
    if(r2.y >r1.y && (r2.y-r1.y) < r2.wid)
      return 1;
   return 0;
}
26. Write a fucntion to find if two triangles are equal. Two triangles are equal if they have same 3 vertices.

#include<stdio.h>
#include<math.h>
struct point
{
   int x;
   int y;
};
struct triangle
{
   struct point p1;
   struct point p2;
   struct point p3;
};
int equal_points(struct point p1,struct point p2)
{
    if(p1.x==p2.x && p1.y == p2.y)
      return 1;
    return 0;
}
int equal_triangles(struct triangle t1, struct triangle t2)
{
   if( equal_points(t1.p1,t2.p1)
       &&  (   (equal_points(t1.p2,t2.p2) &&  equal_points(t1.p3,t2.p3))
              || (equal_points(t1.p3,t2.p2) &&  equal_points(t1.p2,t2.p3) )
           )
       )
            return 1;

   if( equal_points(t1.p1,t2.p2)
       &&  (   (equal_points(t1.p2,t2.p3) &&  equal_points(t1.p3,t2.p1))
              || (equal_points(t1.p2,t2.p1) &&  equal_points(t1.p3,t2.p3) )
           )
      )
           return 1;

 if( equal_points(t1.p1,t2.p3)
       &&  (   (equal_points(t1.p2,t2.p1) &&  equal_points(t1.p3,t2.p2))
              || (equal_points(t1.p2,t2.p1) &&  equal_points(t1.p3,t2.p2) )
           )
     )
            return 1;
   return 0;
}


int main()
{
    struct triangle t1, t2;
    printf("Enter the points  of the triangle 1:");
    scanf("%d %d %d %d %d %d",&t1.p1.x,&t1.p1.y,
                              &t1.p2.x,&t1.p2.y,
                              &t1.p3.x,&t1.p3.y);
    printf("Enter the points  of the triangle 2:");
    scanf("%d %d %d %d %d %d",&t2.p1.x,&t2.p1.y,
                              &t2.p2.x,&t2.p2.y,
                              &t2.p3.x,&t2.p3.y);

     equal_triangles(t1,t2)?printf("equal triangles"):
                printf("not equal triangles");
    return 0;
}
27. Write a function to read the structure point with two members x and y. Use this function to read two points and find the distance between them.

Distance between two points (x1,y1) and (x2,y2) = √( (x2-x1)2 + (y2-y1)2)

#include<stdio.h>
#include<math.h>
struct point
{
   float x;
   float y;
};
void read_point(struct point *ptr)
{
    printf("Enter point:");
    scanf("%f %f",&ptr->x,&ptr->y);
}
double get_distance(struct point p1,struct point p2)
{
    double d =  sqrt( (p2.x-p1.x)*(p2.x-p1.x) + (p2.y-p1.y)*(p2.y-p1.y));
    return d;
}  
int main()
{
   struct point p1,p2;
   double distance ;
   read_point(&p1);
   read_point(&p2);
   distance = get_distance(p1,p2);
   printf("The distance between ( %.2f,%.2f) and ( %.2f,%.2f) is %.2f\n",p1.x,p1.y,p2.x,p2.y,distance);
   return 0;
}

A structure is sent to a function as a call by value parameter. Which means if this structure is read in the function, it will not available in the caller function. That's why the function to read a structure must use a pointer to structure parameter.

28. Write a function to read name and id of a student and return these.

#include<stdio.h>
struct student
{
   int id;
   char name[40];
};
struct student read_info()
{
    struct student temp;
    printf("Enter id and name:");
    scanf("%d %s",&temp.id,temp.name);
    return temp;
}
int main()
{
    struct student s1 = read_info();
    printf("Student's name is %s and id is %d",s1.name,s1.id);
    return 0;
}

A function can return a structure too. Here read_info() function reads the structure and returns it.

29. Write a program to read names and salaries of 10 employees and print the name of employee who gets highest salary.

#include<stdio.h>
typedef struct  
{
   char name[40];
   float salary;
}  EMPL;
EMPL read_empl()
{
   EMPL temp;
   printf("Enter name:");
   scanf("%s",temp.name);
   printf("Enter salary:");
   scanf("%f",&temp.salary);
   return temp;
}

EMPL find_largest_salary(EMPL arr[],int size)
{
    int i;
    int l = 0; 
    for(i=1;i<size;i++)
       if(arr[i].salary>arr[l].salary)
          l = i;
    return arr[l];
}

int main()
{
    EMPL arr[10];
    EMPL rich;
    int i;
    for(i=0;i<10;i++)
       arr[i] = read_empl();
 
    rich = find_largest_salary(arr,10);
    printf("%s gets highest salary and his salary is %.2f\n",rich.name,rich.salary);
    return 0;
}

    
30. How do you define a structure variable? How do you access members of a structure?

First a structure is declared using the syntax

struct tag-name
 {   
        data-type var-name; 
        data-type var-name;
          ....
 };

This is declaration of data type.

e.g
struct student
 {
    int id;
    char name[30];
    float marks;   
 };

Here we are declarating a data type called struct student. We have not yet defined any variable.

To define a variable of struct type, we use struct keyword , tag and variable name.

e.g.
  struct student s1;

s1 is a variable of type struct student.

To access members of structure variable, dot operator is used(.)
s1.id = 3;
  strcpy(s1.name,"Dennis Ritchie");

31. How do you send a structure to a function? Can a function return a structure?

A structure is sent to a function as a parameter by specifying struct keyword, its tag and a variable name.

void print_details(struct student s1)
 {
   printf("Name is %s\n",s1.name);
   ....
 }

But structure parameter is sent using call by value method.

If the function must modify the structure, it has to be sent using structure pointer parameter.
void read_details(struct student *sptr)
  {
        scanf("%d",&sptr->id);
        scanf("%s",sptr->name);
           ...
  }
 int main()
 {
      struct student s1;  
      read_details(&s1); 
      print_details(s1); 
 }
A function can also return a structure.
struct student read() 
{    
  struct student temp;   
  ....   
 return temp; 
}
32. How do you define a union?

A union is similar to a structure. It can have different fields of different types. But at any time, only one field is active. And size of union is not sum of sizes of members but it is size of largest member.
Syntax is

union tag
 {
   type field;
   type field;
  ..
 };

e.g.
union abc 
{    
    int n1;    
    float n2;    
    double n3; 
};
union abc s1;

33. Define a type which is an array of 10 integers as INTARR. Define a data type pointer to pointer to integer as DBLPTR.

typedef int [10] INTARR;
typedef int **DBLPTR;

34. How do you initialize a structure?

A structure is initialized at the time of definition by giving values to its members in curly brackets.

Partially initialized structure is filled with 0 for uninitialized fields.

struct point
{    
      float x,y;
};
int main()
{
   struct point p1 = {1.4,2.1};  
   struct point p2 = {9.1};
   printf("p1 is (%f,%f)",p1.x,p1.y);
   printf("p2 is (%f,%f)",p2.x,p2.y);
}
35. What is an enum? How do you use it?

An enum is an enumerated data type which consists of named values which can be used as constants in program.

enum color {black,white,red,green};
int c = black;

Here black,white etc. are all enumerated values. enum values start with 0 and continue from there.

So here black = 0, white =1, red = 2 and green=3

We can assign values to these named constants. Once a value is assigned, the subsequent values continue from there.
enum color {black, white=5,red,green};

Here black = 0, white=5, red=6 and green=7

36. What are bit fields? How do we use them? What are the restrictions on them?

A bit field is a field of a structure or of a union, whose width is specified in number of bits.

Bit fields are useful in saving memory for fields which have a very small range.

e.g.

struct employee   
{        
   int id;        
   char name[40];        
   unsigned int married:1;        
   unsigned int dept:2;        
   float salary;    
  };

Here married and dept are bit fields which occupy 1 and 2 bits respectively. So we are saving one byte for each struct variable.

We can not have a pointer to bit field as they do not end at word boundaries.