Structures and Union in C

What is Structure data type? 

A structure is a keyword that creates user-defined data types in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. 

Where to use the Structure data type?

We can use this data type to store dates of different attributes of different data types.
For example, If we want to store data on multiple patients such as patient name, age, and blood group.

How to create a structure? 

‘struct’ keyword is used to create a structure. Following is an example.  

struct address
{
   char name[50];
   char street[100];
   char city[50];
   char state[20];
   int pin;
};

How to declare structure variables? 

A structure variable can either be declared with structure declaration or as a separate declaration like basic types. 


// A variable declaration with structure declaration.
struct Point
{
   int x, y;
} p1;  // The variable p1 is declared with 'Point'
 
 
// A variable declaration like basic data types
struct Point
{
   int x, y;
};
 
int main()
{
   struct Point p1;  // The variable p1 is declared like a normal variable
}

Note: In C++, the struct keyword is optional before in declaration of a variable. In C, it is mandatory.
 

How to initialize structure members? 

Structure members cannot be initialized with declaration. For example, the following C program fails in the compilation. 

struct Point
{
   int x = 0;  // COMPILER ERROR:  cannot initialize members here
   int y = 0;  // COMPILER ERROR:  cannot initialize members here
};

The reason for above error is simple, when a datatype is declared, no memory is allocated for it. Memory is allocated only when variables are created.
Structure members can be initialized using curly braces ‘{}’. For example, the following is a valid initialization. 

struct Point
{
   int x, y;
};
 
int main()
{
   // A valid initialization. member x gets value 0 and y
   // gets value 1.  The order of declaration is followed.
   struct Point p1 = {0, 1};
}

How to access structure elements? 

Structure members are accessed using dot (.) operator. 


#include <stdio.h>
 
struct Point {
    int x, y;
};
 
int main()
{
    struct Point p1 = { 0, 1 };
 
    // Accessing members of point p1
    p1.x = 20;
    printf("x = %d, y = %d", p1.x, p1.y);
 
    return 0;
}

Output

x = 20, y = 1

What is designated Initialization? 

Designated Initialization allows structure members to be initialized in any order. This feature has been added in C99 standard


#include <stdio.h>
 
struct Point {
    int x, y, z;
};
 
int main()
{
    // Examples of initialization using designated
    // initialization
    struct Point p1 = { .y = 0, .z = 1, .x = 2 };
    struct Point p2 = { .x = 20 };
 
    printf("x = %d, y = %d, z = %d\n", p1.x, p1.y, p1.z);
    printf("x = %d", p2.x);
    return 0;
}

Output

x = 2, y = 0, z = 1
x = 20

This feature is not available in C++ and works only in C.

What is an array of structures? 

Like other primitive data types, we can create an array of structures. 


#include <stdio.h>
 
struct Point {
    int x, y;
};
 
int main()
{
    // Create an array of structures
    struct Point arr[10];
 
    // Access array members
    arr[0].x = 10;
    arr[0].y = 20;
 
    printf("%d %d", arr[0].x, arr[0].y);
    return 0;
}#include <stdio.h>structPoint {    intx, y;};intmain(){    // Create an array of structures    structPoint arr[10];    // Access array members    arr[0].x = 10;    arr[0].y = 20;    printf("%d %d", arr[0].x, arr[0].y);    return0;}

Output

10 20

What is a structure pointer? 

Like primitive types, we can have a pointer to a structure. If we have a pointer to structure, members are accessed using arrow ( -> ) operator.


#include <stdio.h>
 
struct Point {
    int x, y;
};
 
int main()
{
    struct Point p1 = { 1, 2 };
 
    // p2 is a pointer to structure p1
    struct Point* p2 = &p1;
 
    // Accessing structure members using structure pointer
    printf("%d %d", p2->x, p2->y);
    return 0;
}

Output

1 2

Limitations of C Structures

In C language, Structures provide a method for packing together data of different types. A Structure is a helpful tool to handle a group of logically related data items. However, C structures have some limitations.

  • The C structure does not allow the struct data type to be treated like built-in data types:
  • We cannot use operators like +,- etc. on Structure variables. For example, consider the following code: 
struct number {
    float x;
};
int main()
{
    struct number n1, n2, n3;
    n1.x = 4;
    n2.x = 3;
    n3 = n1 + n2;
    return 0;
}
 
/*Output:
 
prog.c: In function 'main':
prog.c:10:7: error:
invalid operands to binary + (have 'struct number' and
'struct number') n3=n1+n2;
 
*/

But we can use arithmetic operation on structure variables like this.


// Use of arithmetic operator in structure
 
#include <stdio.h>
 
struct number {
    float x;
};
int main()
{
    struct number n1, n2, n3;
    n1.x = 4;
    n2.x = 3;
    n3.x = (n1.x) + (n2.x);
    printf("\n%f", n3.x);
    return 0;
}

Output

7.000000
  • No Data Hiding: C Structures do not permit data hiding. Structure members can be accessed by any function, anywhere in the scope of the Structure
  • Functions inside Structure: C structures do not permit functions inside Structure 
  • Static Members: C Structures cannot have static members inside their body
  • Access Modifiers: C Programming language does not support access modifiers. So they cannot be used in C Structures.
  • Construction creation in Structure: Structures in C cannot have a constructor inside Structures.

Union in C

Like Structures, union is a user defined data type. In union, all members share the same memory location.

For example in the following C program, both x and y share the same location. If we change x, we can see the changes being reflected in y.

#include <stdio.h>
  
// Declaration of union is same as structures
union test {
    int x, y;
};
  
int main()
{
    // A union variable t
    union test t;
  
    t.x = 2; // t.y also gets value 2
    printf("After making x = 2:\n x = %d, y = %d\n\n",
           t.x, t.y);
  
    t.y = 10; // t.x is also updated to 10
    printf("After making y = 10:\n x = %d, y = %d\n\n",
           t.x, t.y);
    return 0;
}        

Output:

After making x = 2:
 x = 2, y = 2

After making y = 10:
 x = 10, y = 10

 
How is the size of union decided by compiler?
Size of a union is taken according the size of largest member in union.

#include <stdio.h>
  
union test1 {
    int x;
    int y;
} Test1;
  
union test2 {
    int x;
    char y;
} Test2;
  
union test3 {
    int arr[10];
    char y;
} Test3;
  
int main()
{
    printf("sizeof(test1) = %lu, sizeof(test2) = %lu, "
           "sizeof(test3) = %lu",
           sizeof(Test1),
           sizeof(Test2), sizeof(Test3));
    return 0;
}

Output:

sizeof(test1) = 4, sizeof(test2) = 4, sizeof(test3) = 40

 
Pointers to unions?
Like structures, we can have pointers to unions and can access members using the arrow operator (->). The following example demonstrates the same.

#include <stdio.h>
  
union test {
    int x;
    char y;
};
  
int main()
{
    union test p1;
    p1.x = 65;
  
    // p2 is a pointer to union p1
    union test* p2 = &p1;
  
    // Accessing union members using pointer
    printf("%d %c", p2->x, p2->y);
    return 0;
}

Output:

65 A

 
What are applications of union?
Unions can be useful in many situations where we want to use the same memory for two or more members. For example, suppose we want to implement a binary tree data structure where each leaf node has a double data value, while each internal node has pointers to two children, but no data. If we declare this as:


struct NODE {
    struct NODE* left;
    struct NODE* right;
    double data;
};

then every node requires 16 bytes, with half the bytes wasted for each type of node. On the other hand, if we declare a node as following, then we can save space.

struct NODE {
    bool is_leaf;
    union {
        struct
        {
            struct NODE* left;
            struct NODE* right;
        } internal;
        double data;
    } info;
};

The above example is taken from Computer Systems : A Programmer’s Perspective (English) 2nd Edition book.

Published by webknowl

Web Application Developer

One thought on “Structures and Union in C

Leave a comment