C Programming - Structures in C
A structure is a heterogeneous user-defined data type which is a collection of dissimilar data items. It is used to represent logically related data items.
Example: If the details like name, register number, marks, and grade are to be stored for a student, a structure template can be defined. This template defines the members and their data types of the new data type which we want to create. Then variables which can store these details can be declared for this new structure data type.
Definition of a structure template
struct tagname //name of the new structure data type
datatype member1; //field or structure elements
. . . .
Now defining a structure for representing the above mentioned student details.
char sname; //These do not occupy any memory until associated with any variable.
The tag name 'student' now is a new data type which the user has created. Like the data type int, float, char, etc, 'student' is also a data type. This data type name (or) tagname can be used to declare variables of this type.
Declaration of structure variables
1) Similar to the declaration of ordinary variables, structure variables can also be declared.
int n; //declares a variable 'n' of data type 'int'. ie., 'n' can hold values up to the maximum limit specified in the definition of 'int'
struct student S; //declares a variable ' S' for the structure data type 'student'
Memory will be allocated only if a variable is declared for a structure. 'S is now a variable which has 4 members for itself. Thus a total of 29 bytes will be allocated for the struct variable, 'S', so that it can store all the 4 details
2) The variable can be declared while defining the structure itself.
} S1, S2;
This also declares 2 variables S1 and S2 for the structure data type 'student'. ('student' is a new data type which the user has defined).
Accessing the structure members
The member or dot (.) operator can be used to access the members of a structure independently.
Syntax: structureVariableName. memberName;
Assuming, we want to access the total marks of the student S2. This can be done by writing S2.total. Always remember that the structure can never be accessed without mentioning the structure variable name and accessing members of a structure using structure tag is not allowed.
struct student_details S1,S2;
printf("enter details for student 1:\n");
scanf("%d%s%d%c", &S1.sno, &S1.name, &S1.total, &S1.grade);
printf("enter details for student 2:\n");
scanf("%d%s%d%c", &S1.sno, &S2.name, &S2.total, &S2.grade);
printf("the details are:\n");
printf("%d%s%d%c", &S1.sno, &S1.name, &S1.total, &S1.grade);
printf("%d%s%d%c", &S1.sno, &S2.name, &S2.total, &S2.grade);
1 Ashok 95 A
2 Vinay 90 A
1 Ashok 95 A
2 Vinay 90 A