Structure
What is a structure in C?
A structure is one of the most important user-defined data types in C. It allows us to combine different types of data under a single name. Structures are especially useful when representing real-world entities such as students, employees, books, and bank accounts.
A structure is a user-defined data type that groups related variables, possibly of different data types, under a single name.
For example, a student may have the following information:
- Roll number — integer
- Name — string
- Marks — floating-point number
- Grade — character
Why do we need structures?
An array can store only elements of the same data type. A student record, however, needs an integer, a string, a floating-point number, and a character together. A structure groups these related values into one unit, so a whole record can be created, stored, copied, and passed to functions under a single name.
Defining a structure
Syntax:
struct structure_name
{
data_type member1;
data_type member2;
data_type member3;
};
Example:
struct Student
{
int rollNo;
char name[30];
float marks;
char grade;
};
The structure definition ends with a semicolon. The variables declared inside it are called members.
Declaring structure variables
After defining a structure, variables of that type can be declared:
struct Student s1;
Accessing structure members
The dot operator (.) accesses a member through a structure variable.
#include <stdio.h>
struct Student
{
int rollNo;
char name[30];
float marks;
char grade;
};
int main( )
{
struct Student s1;
s1.rollNo = 101;
snprintf(s1.name, sizeof s1.name, "%s", "Naveen");
s1.marks = 87.5f;
s1.grade = 'A';
printf("Roll Number: %d\n", s1.rollNo);
printf("Name : %s\n", s1.name);
printf("Marks : %.2f\n", s1.marks);
printf("Grade : %c\n", s1.grade);
return 0;
}
Output:
Roll Number: 101
Name : Naveen
Marks : 87.50
Grade : A
The statement s1.marks = 87.5f; assigns a value to the marks member of s1. Similarly, s1.grade = 'A'; assigns a character to the grade member.
Initializing a structure
Structure members can be initialized when the structure variable is declared.
Example 1: Initialization in declaration order
#include <stdio.h>
struct Student
{
int rollNo;
char name[30];
float marks;
};
int main( )
{
struct Student s1 = {101, "Naveen", 87.5f};
printf("%d\n", s1.rollNo);
printf("%s\n", s1.name);
printf("%.2f\n", s1.marks);
return 0;
}
Output:
101
Naveen
87.50
The values are assigned in the order in which the members are declared:
| Member | Initial value |
|---|---|
| rollNo | 101 |
| name | "Naveen" |
| marks | 87.5f |
Example 2: Designated initializers
In C99 and later, designated initializers allow members to be initialized by name.
struct Student s1 = {
.marks = 87.5f,
.rollNo = 101,
.name = "Naveen"
};
The order of the initializers does not have to match the declaration order when designated initializers are used.
Example 3: Partial initialization
struct Student s1 = {101};
Here, rollNo is initialized to 101, while the remaining members are initialized to zero values (including an empty string in the first character of name) because this is aggregate initialization.
Reading structure members from the user
The following program accepts student details through keyboard input.
#include <stdio.h>
struct Student
{
int rollNo;
char name[30];
float marks;
};
int main( )
{
struct Student s1;
printf("Enter roll number: ");
if (scanf("%d", &s1.rollNo) != 1)
return 1;
printf("Enter name: ");
if (scanf("%29s", s1.name) != 1)
return 1;
printf("Enter marks: ");
if (scanf("%f", &s1.marks) != 1)
return 1;
printf("\n--- Student Details ---\n");
printf("Roll Number: %d\n", s1.rollNo);
printf("Name : %s\n", s1.name);
printf("Marks : %.2f\n", s1.marks);
return 0;
}
Sample output:
Enter roll number: 101
Enter name: Naveen
Enter marks: 87.5
--- Student Details ---
Roll Number: 101
Name : Naveen
Marks : 87.50
Important points:
- Use & with s1.rollNo and s1.marks in scanf(), because they are numeric variables.
- Do not use & with s1.name in this example, because the array name already converts to a pointer to its first element.
- %29s limits the input width so the input fits in name[30], leaving space for '\0'.
- %s reads only one word. To read a full name containing spaces, use fgets() with appropriate newline handling.
Array of structures
An array of structures stores multiple records of the same structure type.
For example, to store the details of five students, we can declare:
struct Student students[5];
Program to store and display multiple students
#include <stdio.h>
struct Student
{
int rollNo;
char name[30];
float marks;
};
int main( )
{
struct Student s[3];
int i;
for (i = 0; i < 3; i++)
{
printf("Enter roll number, name and marks: ");
if (scanf("%d %29s %f",
&s[i].rollNo,
s[i].name,
&s[i].marks) != 3)
{
printf("Invalid input\n");
return 1;
}
}
printf("\nStudent Details\n");
for (i = 0; i < 3; i++)
{
printf("%d %s %.2f\n",
s[i].rollNo,
s[i].name,
s[i].marks);
}
return 0;
}
Example input:
101 Naveen 87.5
102 Madhu 91
103 Arun 78
Output:
Student Details
101 Naveen 87.50
102 Madhu 91.00
103 Arun 78.00
Here, s[i].rollNo accesses the roll number of the ith student. The same pattern is used to access other members.
Nested structures
A nested structure is a structure that contains another structure as one of its members.
For example, a student record may contain an address.
#include <stdio.h>
struct Address
{
char city[30];
int pinCode;
};
struct Student
{
int rollNo;
char name[30];
struct Address address;
};
int main( )
{
struct Student s1 = {
101, "Naveen", {"Hyderabad", 500001}
};
printf("Name: %s\n", s1.name);
printf("City: %s\n", s1.address.city);
printf("PIN Code: %d\n", s1.address.pinCode);
return 0;
}
Output:
Name: Naveen
City: Hyderabad
PIN Code: 500001
Notice the member access:
s1.address.city
First, s1.address accesses the address structure inside s1. Then .city accesses the city member of that nested structure.
Nested structures are useful for representing addresses, dates, departments, and other grouped information.
Pointer to a structure
A pointer to a structure stores the address of a structure variable.
Declaration syntax:
struct Student *ptr;
A pointer can be initialized with the address of a structure variable using the address-of operator (&).
Example program
#include <stdio.h>
struct Student
{
int rollNo;
char name[30];
float marks;
};
int main( )
{
struct Student s1 = {101, "Naveen", 87.5f};
struct Student *ptr = &s1;
printf("Roll Number: %d\n", ptr->rollNo);
printf("Name : %s\n", ptr->name);
printf("Marks : %.2f\n", ptr->marks);
return 0;
}
Output:
Roll Number: 101
Name : Naveen
Marks : 87.50
The arrow (->) operator
The arrow operator accesses a structure member through a pointer.
These two expressions are equivalent:
ptr->marks
(*ptr).marks
The parentheses in (*ptr).marks are important because the dot operator has higher precedence than the unary * operator.
Passing a structure to a function
A structure variable can be passed to a function just like other values. When a structure is passed by value, the function receives its own copy of the structure.
Example: Passing a structure by value
#include <stdio.h>
struct Student
{
int rollNo;
char name[30];
float marks;
};
void display(struct Student s)
{
printf("Roll Number: %d\n", s.rollNo);
printf("Name : %s\n", s.name);
printf("Marks : %.2f\n", s.marks);
}
int main( )
{
struct Student s1 = {101, "Naveen", 87.5f};
display(s1);
return 0;
}
Output:
Roll Number: 101
Name : Naveen
Marks : 87.50
Here, display(s1) passes the structure value to the function. The parameter s is a separate structure object initialized from the argument.
Exam point: Changes to ordinary members of the copied parameter do not change the corresponding members of the original structure. If a structure contains pointers, however, the copied pointers can still refer to the same underlying objects.
Passing a pointer to a structure to a function
Passing a pointer allows a function to access the original structure without copying the entire structure.
#include <stdio.h>
struct Student
{
int rollNo;
char name[30];
float marks;
};
void updateMarks(struct Student *s)
{
s->marks = 95.0f;
}
int main( )
{
struct Student s1 = {101, "Naveen", 87.5f};
updateMarks(&s1);
printf("Updated marks = %.2f\n", s1.marks);
return 0;
}
Output:
Updated marks = 95.00
Explanation
- &s1 passes the address of the original structure.
- The function parameter s receives that address.
- s->marks accesses and modifies the original structure's marks member.
Returning a structure from a function
In C, a function can return a structure value.
#include <stdio.h>
struct Point
{
int x;
int y;
};
struct Point createPoint(void)
{
struct Point p = {10, 20};
return p;
}
int main( )
{
struct Point p1 = createPoint();
printf("x = %d\n", p1.x);
printf("y = %d\n", p1.y);
return 0;
}
Output:
x = 10
y = 20
The function createPoint() returns a struct Point value, which is assigned to p1.
Using typedef with structures
The typedef keyword creates an alias for a type. It can make structure declarations shorter.
Without typedef:
struct Student s1;
With typedef:
typedef struct
{
int rollNo;
char name[30];
float marks;
} Student;
int main( )
{
Student s1 = {101, "Naveen", 87.5f};
return 0;
}
Now, we can write Student s1; instead of struct Student s1;.
Remember: typedef creates an alias for a type; it does not create a variable or allocate memory by itself.
Self-referential structures
A self-referential structure contains a pointer to another object of the same structure type. It is commonly used to implement linked lists, trees, and graphs.
Example:
struct Node
{
int data;
struct Node *next;
};
Here, next can point to another struct Node.
A structure cannot contain a direct member of its own type, such as struct Node next;, because that would require each node to contain another complete node indefinitely. A pointer has a fixed size and can refer to another node, so it solves this problem.
Structure memory allocation and padding
When a structure variable is created, memory is allocated to store its members. However, the total size of a structure is not necessarily equal to the sum of the sizes of its members.
Compilers may insert extra bytes called padding to satisfy alignment requirements.
Example:
#include <stdio.h>
struct Example
{
char ch;
int num;
};
int main( )
{
printf("Size of char = %zu bytes\n", sizeof(char));
printf("Size of int = %zu bytes\n", sizeof(int));
printf("Size of structure = %zu bytes\n",
sizeof(struct Example));
return 0;
}
The exact size of struct Example depends on the C implementation. A common implementation uses 1 byte for char, 4 bytes for int, and 3 padding bytes between them, making the structure size 8 bytes.
Important rules to remember
- Structure members can have different data types.
- The structure definition ends with a semicolon.
- Use the dot operator (.) to access members through a structure variable.
- Use the arrow operator (->) to access members through a pointer to a structure.
- Arrays of structures can store multiple records.
- A structure can be passed to a function by value or through a pointer.
- A function can return a structure value.
- typedef can simplify structure type declarations.
- Self-referential structures use pointers to the same structure type.
- sizeof gives the actual size, including any padding.