Nearby lessons

59 of 72

C - Structure Initialisation

Structure initialisation means giving values to structure members when a variable is created. This lesson covers the basic brace method and what happens when some values are not provided.

1. Basic Structure Initialisation

Give the values inside braces when declaring the structure variable. The values follow the order in which members are defined.

Example01
CCode Cell
1#include <stdio.h>
2 
3struct Student {
4 int rollNo;
5 char name[30];
6 float marks;
7};
8 
9int main(void) {
10 struct Student s1 = {101, "Rahul", 88.5f};
11 
12 printf("Roll Number: %d\n", s1.rollNo);
13 printf("Name: %s\n", s1.name);
14 printf("Marks: %.1f\n", s1.marks);
15 
16 return 0;
17}
Output
Roll Number: 101
Name: Rahul
Marks: 88.5

2. The Order of Values Matters

In a normal brace initialiser, the first value goes to the first member, the second value goes to the second member, and so on. Keep the order correct.

Example02
CCode Cell
1#include <stdio.h>
2 
3struct Point {
4 int x;
5 int y;
6};
7 
8int main(void) {
9 struct Point p1 = {10, 20};
10 
11 printf("x = %d\n", p1.x);
12 printf("y = %d\n", p1.y);
13 
14 return 0;
15}
Output
x = 10
y = 20

3. Partial Initialisation

If you provide fewer values than the structure has members, the remaining members are set to zero.

Example03
CCode Cell
1#include <stdio.h>
2 
3struct Point {
4 int x;
5 int y;
6 int z;
7};
8 
9int main(void) {
10 struct Point p1 = {10};
11 
12 printf("x = %d\n", p1.x);
13 printf("y = %d\n", p1.y);
14 printf("z = %d\n", p1.z);
15 
16 return 0;
17}
Output
x = 10
y = 0
z = 0

4. Initialise All Members to Zero

Use {0} to initialise the whole structure to zero. This is a simple and useful option when you want a clean starting value.

Example04
CCode Cell
1#include <stdio.h>
2 
3struct Student {
4 int rollNo;
5 char name[30];
6 float marks;
7};
8 
9int main(void) {
10 struct Student s1 = {0};
11 
12 printf("Roll Number: %d\n", s1.rollNo);
13 printf("Name: %s\n", s1.name);
14 printf("Marks: %.1f\n", s1.marks);
15 
16 return 0;
17}
Output
Roll Number: 0
Name:
Marks: 0.0

Common Mistakes

  • Do not provide values in the wrong order.
  • Do not assume an uninitialised local structure contains zeros.
  • Use braces at the time of declaration, for example struct Point p = {10, 20};.
📝 Key Takeaways
  • Use braces to provide initial values.
  • Values in a basic initialiser follow the order of the structure members.
  • Members not provided in an initialiser are set to zero.
  • Use {0} when you want to initialise all members to zero.
  • A local structure declared without an initialiser is not automatically set to zero.

🧠 Test Your Knowledge

2 Questions
Progress: 0 / 2