In C programming language, a structure is a composite data type that groups together related data items of different data types under a single name. Structures are defined using the struct
keyword, which defines a new type that can be used to declare variables of that type.
Here's the syntax for defining a structure:
struct <structure_name> {
<data_type_1> <member_name_1>;
<data_type_2> <member_name_2>;
// ...
};
For example, let's define a Person
structure that represents a person's name, age, and address:
struct Person {
char name[50];
int age;
char address[100];
};
Once a structure is defined, you can declare variables of that type:
struct Person p1;
You can also initialize a structure variable at the time of declaration:
struct Person p2 = {"John Doe", 30, "123 Main St"};
You can access individual members of a structure using the dot (.
) operator:
p1.age = 25;
printf("Name: %s\nAge: %d\nAddress: %s\n", p2.name, p2.age, p2.address);
You can also use pointers to structures, which are declared using the struct
keyword followed by a pointer variable name:
struct Person *ptr = &p1;
ptr->age = 40;
Here's an example program that demonstrates the use of structures in C:
#include <stdio.h>
struct Person {
char name[50];
int age;
char address[100];
};
int main() {
struct Person p1;
struct Person p2 = {"John Doe", 30, "123 Main St"};
p1.age = 25;
printf("Name: %s\nAge: %d\nAddress: %s\n", p2.name, p2.age, p2.address);
struct Person *ptr = &p1;
ptr->age = 40;
printf("Name: %s\nAge: %d\nAddress: %s\n", p1.name, p1.age, p1.address);
return 0;
}
This program declares two Person
structures p1
and p2
, initializes p2
with some values, updates p1
's age using a pointer, and prints out the values of the members for both structures.
Comments