Structures, Typedef and Union in C Programming

Here we’ll learn about Structures, Typedef and Union in C Programming Language. If you recall from previous lesson, arrays are group of item of same type under one variable name. The Structures or struct is user-defined data type in C which allows grouping together related data items of different types. Structures are useful to construct a complex data type in more meaningful way. Structures are often used to represent record. Let’s take example, if we wish to store record of Book which consists of Book Name, No. of Pages and Price. We will define structure to hold this information of different types like name is string, No. of Pages will be integer and Price will be float value.

learn-embedded-system

Definition of Structure

The struct keyword is used to define structure. The struct define a new data type which is collection of different type of data. In our example Book is a structure.

struct Book{
    char *name;
    int pages;
    float price;
};

This is how we can define structure. To use structure in C Programs, we have to declare structure variable. There are two ways we can do this. We can declare structure variable separately or with structure definition. Let’s have a look at each case.

Declaring Structure Variable separately
struct Book{
    char *name;
    int pages;
    float price;
};
struct Book B1, B2;   //declaring variables of type Book
Declaring Structure Variable with Structure definition
struct Book{
    char *name;
    int pages;
    float price;
} B1, B2; 

Here B1 and B2 are variables of type Book. At the end of the structure’s definition before the final semicolon, we can specify one or more structure variables but it is optional. However, this second approach is not much recommended. In all of our example code we are going to declare structure variable separately.

Example: Here is a simple example project. We will define structure name Book and also access structure members.
#include<stdio.h>

struct Book{
    char *name;
    int pages;
    float price;
};

int main()
{
    struct Book B1;     // B1 is variable of type Book

    B1.name = "Handbook of C";
    B1.pages = 750;
    B1.price = 125.50;

    printf("Name of Book: %s\n", B1.name);
    printf("No. of Pages: %d\n", B1.pages);
    printf("Price       : %f\n", B1.price);

    return 0;
}

Explanation: In above example we have structure Book. The Book structure has three member variables name, pages and price. Structure members can be accessed and assigned values in number of ways. In order to assign a value to a structure member, the member name must be linked with the structure variable using dot (.) operator. Let’s assign name to variable Book by simply writing statement B1.name = “Handbook of C”. This is a reason when we print B1.name, we’ll get Handbook of C printed on screen. The same rule applies to all other member variables.

Structures in C Programming
Structures in C Programming

Typedef and Structures in C Programming

The keyword Typedef is used to give a new symbolic name for the existing name. Typedef is type definitions make code more readable by giving application-specific names to types. In this example, we will create type definition with structures. The name of type definition of a structure is usually in upper case letters.

#include<stdio.h>

typedef struct Book{
    char *name;
    int pages;
    float price;
}BOOK;

int main()
{
    BOOK index;

    index.name = "Handbook of C";
    index.pages = 750;
    index.price = 125.50;

    printf("Name of Book: %s\n", index.name);
    printf("No. of Pages: %d\n", index.pages);
    printf("Price       : %f\n", index.price);

    return 0;
}

Usually, Typedef will be placed into header file and use type names in main program. If definition of Book changes, we might not need to change the code in our main program file. Typedef interpretation is performed by compiler. There may be some reader confuse with #define and typedef. We will discuss their use cases in separate lesson.

Pointer to Structures

If we want a pointer to a structure we have to use the -> (arrow operator) instead of a dot. Take a look at the following example:

#include<stdio.h>

typedef struct Book{
    char *name;
    int pages;
    float price;
}BOOK;

int main()
{
    BOOK index;
    BOOK *ptr_myindex;

    ptr_myindex = &index;

    ptr_myindex->name = "Handbook of C";
    ptr_myindex->pages = 750;
    ptr_myindex->price = 125.50;

    printf("Name of Book: %s\n", ptr_myindex->name);
    printf("No. of Pages: %d\n", ptr_myindex->pages);
    printf("Price       : %f\n", ptr_myindex->price);

    return 0;
}

Note: The -> (Arrow operator) is also used in the printf statement.

Union in C Programming

Unions are conceptually similar to Structures. The only difference between them is memory allocation. Structure allocates storage space for all its members separately; Whereas, Union allocates one common storage space for all its members. Members of a union can only be accessed one at a time. The union data type was invented to prevent memory fragmentation. The union data type prevents fragmentation by creating a standard size of certain data everything else remains same as Structures.

#include<stdio.h>
#include<string.h>

typedef union Book{
    int pages;
    float price;
    char name[20];
};

int main()
{
    union Book index;

    index.pages = 750;
    index.price = 125.50;
    strcpy(index.name, "Handbook of C");

    printf("Name of Book: %s\n", index.name);
    printf("No. of Pages: %d\n", index.pages);
    printf("Price       : %f\n", index.price);

    return 0;
}

Let’s build and run this example code and observe output.

Output of Union in C Programming
Output of Union in C Programming

Here, we can see that the values of pages and price members of union got corrupted because the final value assigned to the variable has occupied the memory location and this is the reason that the value of name member is getting printed very well. As we know union can only access one member at a time. The following code will be corrected version of this example.

#include<stdio.h>
#include<string.h>

typedef union Book{
    int pages;
    float price;
    char name[20];
};

int main()
{
    union Book index;

    strcpy(index.name, "Handbook of C");
    printf("Name of Book: %s\n", index.name);

    index.pages = 750;
    printf("No. of Pages: %d\n", index.pages);

    index.price = 125.50;
    printf("Price       : %f\n", index.price);

    return 0;
}

Let’s build and run this example code and observe output. Here we will get expected output.

Correction in Union in C Programming
Correction in Union in C Programming

This is it for Structures, Typedef and Union in C Programming. We hope you have enjoyed reading this lesson. In next lesson, we’ll learn about Dynamic Memory Allocation in C Programming. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading.

Get Free Courses & Webinars
You'll receive only high quality learning material, tips & tricks
I agree to have my personal information transfered to MailChimp ( more information )
We respect your privacy

About Umesh Lokhande

Umesh Lokhande holds a Master degree in Scientific Instrumentation from University of Applied Sciences Jena, Germany. and has previously worked at Orbotech, Alere Technologies etc. Umesh is also a founder and first author of BINARYUPDATES.COM

Login

Register | Lost your password?