C Structures
A structure in C is a composite data type that groups together variables of different data types under a single name. Structures are used to store data that has several different elements and can be used to represent real-world objects, such as a person's name, age, and address.
struct syntax:
1struct structure_name 2{ 3 type member_name1; 4 type member_name2; 5 type member_name3; 6 ... 7};
Once a structure has been defined, you can declare variables of that structure type using the structure name. For example:
1struct person 2{ 3 char name[50]; 4 int age; 5 char address[100]; 6}; 7 8struct person p1;
You can access the members of a structure using the dot operator (.
). For example:
1p1.age = 25; 2p1.name = "William Mike"; 3strcpy(p1.address, "123 Main Street");
Example: Structures in C
The following example demonstrates the use of structures in C:
1#include <stdio.h> 2#include <string.h> 3 4struct person 5{ 6 char name[50]; 7 int age; 8 char address[100]; 9}; 10 11int main() 12{ 13 struct person p1; 14 strcpy(p1.name, "William Mike"); 15 p1.age = 25; 16 strcpy(p1.address, "123 Main Street"); 17 printf("Name: %s\n", p1.name); 18 printf("Age: %d\n", p1.age); 19 printf("Address: %s\n", p1.address); 20 return 0; 21}
The output of this program is:
1Name: William Mike 2Age: 25 3Address: 123 Main Street
In this example, a structure named person
is defined with three members: name
, age
, and address
. A variable p1
of type person
is declared and initialized with values for its members. The values of the members of p1
are then printed to the console.