A structure in C is a user-defined data type that allows you to group together different types of data under a single name. A structure can be thought of as a container that holds related data of different types.
Why Use Structures:
Structures are useful for organizing complex data structures in a program. By grouping related data together in a structure, you can make your code more readable and easier to maintain.Declaring a Structure:
To declare a structure, you use the struct keyword followed by the structure name and the members of the structure enclosed in curly braces.Example:
cstruct student {
char name[50];
int roll_no;
float marks;
};
Accessing Structure Elements:
You can access the members of a structure using the dot operator (.) followed by the member name.Example:
cstruct student s;
strcpy(s.name, "John");
s.roll_no = 1234;
s.marks = 85.5;
How Structure Elements are Stored:
The elements of a structure are stored in contiguous memory locations. The size of a structure is determined by the sum of the sizes of its members, but the actual size may be larger due to padding.Array of Structures:
An array of structures is a collection of structures of the same type. You can access the members of a structure in an array using the array index and the dot operator.Example:
cstruct student s[3];
s[0].roll_no = 1234;
s[1].roll_no = 2345;
s[2].roll_no = 3456;
No comments:
Post a Comment
Tell us how you like it.