Back to C Programming
2026-02-038 min read

struct initialization

Learn struct initialization step by step with clear examples and exercises.

Why This Matters

Struct initialization is a crucial concept in C programming that allows developers to create and initialize structures with specific values for each member during declaration. In this full guide, we delve into the intricacies of struct initialization, providing practical examples, common mistakes, practice questions, and answers to frequently asked questions. Let's get started!

Why This Matters

Struct initialization is essential in C programming as it enables us to create complex data structures that can hold multiple variables of different types. Structures are often used to represent real-world objects such as points, rectangles, and employees. Proper struct initialization ensures that these objects are created with the correct values, which is crucial for maintaining program correctness and avoiding runtime errors.

Prerequisites

To understand this guide, you should be familiar with the following concepts:

  • Basic C syntax, including variables, data types, and operators
  • Structures and their declaration in C
  • Pointers and memory allocation in C

If you're not already familiar with these topics, we recommend reviewing our lessons on C Basics, Structures in C, and Pointers in C before proceeding.

Core Concept

Struct Definition

Before we dive into struct initialization, let's first review how to define a structure in C:

struct Point {
int x;
int y;
};

In the above example, we have defined a structure named Point, which consists of two integer members: x and y.

Struct Initialization

Now that we have our structure defined, let's see how to initialize it with specific values for each member. In C, struct initialization can be done using the following syntax:

struct Point point1 = { .x = 3, .y = 4 };

In this example, we have initialized a Point structure named point1 with x set to 3 and y set to 4. Note that we use the dot notation (.) to specify which member we want to initialize and the equal sign (=) to assign the corresponding value.

Nested Initialization

If your structure contains other structures or arrays, you can initialize them as well using nested initializations:

struct Rectangle {
struct Point topLeft;
struct Point bottomRight;
};

struct Rectangle rect = { .topLeft = { .x = 0, .y = 0 }, .bottomRight = { .x = 5, .y = 5 } };

In this example, we have defined a Rectangle structure that consists of two Point structures: topLeft and bottomRight. We then initialize the rect variable with specific values for each point. Note how we use nested dot notation to access the members of the inner structures.

Default Initialization

If you don't specify an initial value for a member, it will be automatically initialized to zero or a null pointer (for pointers). For example:

struct Point point2;
printf("%d %d\n", point2.x, point2.y); // Outputs 0 0

In this example, we have declared an uninitialized Point structure named point2. When we print its members, they both have the default value of zero.

Struct Initialization with Arrays

You can also initialize arrays of structures using the same syntax as regular structures:

struct Point points[3] = { [0] = { .x = 1, .y = 2 }, [1] = { .x = 3, .y = 4 }, [2] = { .x = 5, .y = 6 } };

In this example, we have initialized an array of Point structures named points. We use the index operator ([]) to specify which element we want to initialize and follow the same dot notation syntax as before.

Struct Initialization with Pointers

If your structure contains pointers, you can initialize them using the following syntax:

struct Employee {
char name[50];
int age;
float salary;
char* department;
};

struct Employee employee = { .name = "John Doe", .age = 30, .salary = 50000, .department = malloc(strlen("Engineering") + 1) };
strcpy(employee.department, "Engineering");

In this example, we have initialized a Employee structure named employee. We use the dot notation to initialize all members except for department, which is a pointer. To properly allocate memory for the department member, we first call malloc() and then use strcpy() to copy the string "Engineering" into the allocated memory.

Zero-Initialization vs. Default Initialization

Zero-initialization (also known as value initialization) sets all members of a structure to zero or null pointers, regardless of their data types. This can be achieved by using an empty set of curly braces {} during struct initialization:

struct Point point3 = {};
printf("%d %d\n", point3.x, point3.y); // Outputs 0 0

Default initialization (also known as aggregate initialization) sets all array elements and structure members to their respective default values based on their data types. This can be achieved by using an empty set of curly braces {} during struct initialization or simply omitting the initializers for some members:

struct Point point4 = { .x = 3 };
printf("%d %d\n", point4.x, point4.y); // Outputs 0 0

Static Assertion (#pragma GCC diagnostic assert)

You can use the #pragma GCC diagnostic assert directive to ensure that your struct initialization matches the structure definition:

struct Point {
int x;
int y;
};

#pragma GCC diagnostic assert(offsetof(Point, x) == 0 && offsetof(Point, y) == sizeof(int))

This directive will generate a compilation error if the structure definition or member order changes in the future, helping you catch potential issues early.

Worked Example

Let's work through a practical example to illustrate struct initialization in C:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct Point {
int x;
int y;
};

struct Rectangle {
struct Point topLeft;
struct Point bottomRight;
};

struct Employee {
char name[50];
int age;
float salary;
char* department;
};

#pragma GCC diagnostic assert(offsetof(Point, x) == 0 && offsetof(Point, y) == sizeof(int))
#pragma GCC diagnostic assert(offsetof(Rectangle, topLeft) == 0 && offsetof(Rectangle, bottomRight) == sizeof(struct Point))
#pragma GCC diagnostic assert(offsetof(Employee, name) == 0 && offsetof(Employee, age) == sizeof(char[50]))
#pragma GCC diagnostic assert(offsetof(Employee, salary) == offsetof(Employee, age) + sizeof(int))
#pragma GCC diagnostic assert(offsetof(Employee, department) == offsetof(Employee, salary) + sizeof(float))

int main() {
struct Point point1 = { .x = 3, .y = 4 };
struct Point point2 = { 5, 6 }; // y is initialized implicitly
struct Rectangle rect = { .topLeft = { .x = 0, .y = 0 }, .bottomRight = { .x = 5, .y = 5 } };
struct Employee employee = { .name = "John Doe", .age = 30, .salary = 50000, .department = malloc(strlen("Engineering") + 1) };
strcpy(employee.department, "Engineering");

printf("point1: %d %d\n", point1.x, point1.y); // Outputs 3 4
printf("point2: %d %d\n", point2.x, point2.y); // Outputs 5 6
printf("rect:\n");
printf("Top left: %d %d\n", rect.topLeft.x, rect.topLeft.y); // Outputs 0 0
printf("Bottom right: %d %d\n", rect.bottomRight.x, rect.bottomRight.y); // Outputs 5 5
printf("employee:\n");
printf("Name: %s\n", employee.name); // Outputs John Doe
printf("Age: %d\n", employee.age); // Outputs 30
printf("Salary: %f\n", employee.salary); // Outputs 50000.00
printf("Department: %s\n", employee.department); // Outputs Engineering

free(employee.department);

return 0;
}

In this example, we have defined a Point, Rectangle, and Employee structure and initialized them with specific values using both explicit and implicit initialization methods. We then print the values of each member to verify that they were correctly initialized. Finally, we free the memory allocated for the department pointer in the employee structure.

Common Mistakes

  1. Forgetting to initialize all members: If you don't initialize all members of a structure, some will be automatically set to zero or null pointers. However, this can lead to unexpected behavior if you rely on those uninitialized values in your code.
  1. Incorrect member order: When initializing a structure using the comma-separated list method, the order of the members matters. If you initialize them in the wrong order, you may end up with incorrect values for some members.
  1. Using the wrong initialization syntax: Make sure to use the correct syntax for struct initialization—either brace-enclosed, comma-separated lists or dot notation. Mixing these methods can lead to compilation errors.
  1. Trying to initialize a structure with too few initializers: If you provide fewer initializers than there are members in your structure, you will receive a compilation error. Make sure to initialize all members, even if you set them to default values.
  1. Forgetting to free dynamically allocated memory: When using pointers in structures, don't forget to free the memory you've allocated when it's no longer needed. In our example above, we allocate memory for the department pointer in the employee structure and then free it at the end of the program.
  1. Not using static assertions: Static assertions can help catch potential issues early by ensuring that your struct initialization matches the structure definition.

Practice Questions

  1. Write a C program that defines a Student structure containing name, age, grade, and gender. Initialize an instance of the Student structure with the following values: name = "Alice", age = 20, grade = 85, gender = 'F'.
  1. Modify the previous example to add another member called schoolId (of type int) to the Student structure. Initialize the schoolId as 123456 for Alice.
  1. Write a C program that defines a Circle structure containing radius, x, and y. Initialize an instance of the Circle structure with the following values: radius = 5, x = 0, y = 0. Calculate and print the area of the circle using the formula πr².
  1. Write a C program that defines a Person structure containing name, age, and gender. Initialize an array of three Person structures with the following values:
  • Person 1: name = "Alice", age = 20, gender = 'F'
  • Person 2: name = "Bob", age = 25, gender = 'M'
  • Person 3: name = "Charlie", age = 30, gender = 'M'

Print the names and ages of all persons.

FAQ

  1. Why should I use struct initialization instead of assigning values later in my code?

Using struct initialization ensures that your structures are created with the correct initial values, which can help prevent runtime errors and make your code more robust. Assigning values later in your code may introduce bugs if you forget to initialize certain members or assign them incorrect values.

  1. Can I use struct initialization for arrays of structures?

Yes! You can initialize arrays of structures using the same syntax as regular structures, but with an additional index to specify which element you want to initialize. For example:

struct Point points[3] = { [0]