A structure is a user-defined data type in C that groups related variables of different data types into a single unit. It is used to represent a complex data entity such as a record.
struct structure_name {
data_type member1;
data_type member2;
...
};
struct Student {
int roll_no;
char name[50];
float marks;
};
Directly:
struct Student s1;
During Definition:
struct Student {
int roll_no;
char name[50];
float marks;
} s1, s2;
Use the dot operator (.
) to access members of a structure.
s1.roll_no = 101;
strcpy(s1.name, "Alice");
s1.marks = 95.5;
printf("Roll No: %d\n", s1.roll_no);
printf("Name: %s\n", s1.name);
printf("Marks: %.2f\n", s1.marks);
You can create an array of structures to store multiple records.
struct Student students[3];
students[0].roll_no = 101;
strcpy(students[0].name, "Alice");
students[0].marks = 95.5;
students[1].roll_no = 102;
strcpy(students[1].name, "Bob");
students[1].marks = 88.0;
for (int i = 0; i < 2; i++) {
printf("Student %d: %s, %.2f\n", students[i].roll_no, students[i].name, students[i].marks);
}
A structure can have another structure as a member.
struct Address {
char city[30];
int zip;
};
struct Student {
int roll_no;
char name[50];
struct Address addr;
};
struct Student s = {101, "Alice", {"New York", 10001}};
printf("City: %s, ZIP: %d\n", s.addr.city, s.addr.zip);
Structures can be passed to functions by value or by reference.
void display(struct Student s) {
printf("Name: %s\n", s.name);
printf("Marks: %.2f\n", s.marks);
}
void modify(struct Student *s) {
s->marks += 5; // Using arrow operator for pointers
}
You can use pointers to access and modify structure members.
struct Student *ptr = &s1;
ptr->marks = 90.0; // Arrow operator (->) for accessing members
typedef
allows creating a shorthand for structure definitions.
typedef struct {
int roll_no;
char name[50];
float marks;
} Student;
Student s1; // No need to write 'struct'
You can allocate memory for structures dynamically using malloc
.
struct Student *ptr = (struct Student *)malloc(sizeof(struct Student));
ptr->roll_no = 101;
strcpy(ptr->name, "Alice");
ptr->marks = 95.5;
free(ptr); // Freeing allocated memory
Structure | Array |
---|---|
Can store multiple data types. | Can store only one data type. |
Members accessed via names. | Elements accessed via indices. |
Size depends on members. | Size is fixed by type and length. |