In C programming language, a structure is a user-defined data type that groups together variables of different data types under a single name. Structures enable the programmer to create complex data structures that can be easily manipulated in a program.
To declare a structure in C, you need to define its members and their data types. Here’s an example of how to declare a structure in C:
struct Person { char name[50]; int age; float height; };
In this example, we declare a structure named “Person” that has three members: a character array named “name” with a maximum size of 50 characters, an integer named “age”, and a float named “height”.
We can create variables of the structure type by using the “struct” keyword followed by the structure name. Here’s an example of how to create a variable of the “Person” structure type:
struct Person p1;
In this example, we create a variable named “p1” of the “Person” structure type.
We can access the members of a structure variable using the dot operator “.”. Here’s an example of how to access the members of a “Person” structure variable:
struct Person p1; strcpy(p1.name, "John"); p1.age = 30; p1.height = 1.75; printf("Name: %s\n", p1.name); printf("Age: %d\n", p1.age); printf("Height: %.2f\n", p1.height);
In this example, we create a “Person” structure variable named “p1” and initialize its members with the values “John”, 30, and 1.75. We then use the dot operator “.” to access the members of the “p1” variable and print them to the console using printf().
We can also use pointers to manipulate structure variables in C. Here’s an example of how to use a pointer to access the members of a “Person” structure variable:
struct Person p1; struct Person *ptr = &p1; strcpy(ptr->name, "John"); ptr->age = 30; ptr->height = 1.75; printf("Name: %s\n", ptr->name); printf("Age: %d\n", ptr->age); printf("Height: %.2f\n", ptr->height);
In this example, we create a “Person” structure variable named “p1” and a pointer named “ptr” that points to the “p1” variable. We use the -> operator to access the members of the “p1” variable through the pointer and print them to the console using printf().
Structures in C are a powerful feature that enable the programmer to create complex data structures that can be easily manipulated in a program. However, it is important to use structures carefully to avoid memory alignment and padding issues.