Back to C Programming
2026-07-135 min read

Create struct variables

Learn Create struct variables step by step with clear examples and exercises.

Why This Matters

Welcome to this detailed guide on creating struct variables in C programming! This lesson is designed to help you understand how to define and use structures, a fundamental concept in C that allows us to group related data types together. By the end of this tutorial, you'll be able to create your own custom data structures and manipulate them effectively.

Why This Matters

Structures (often abbreviated as "structs") are essential for organizing complex data in C programs. They enable us to represent real-world objects with multiple attributes, making our code more readable and manageable. Structures are useful in various scenarios, such as:

  1. Programming games or simulations where we need to store game objects like players, items, or enemies.
  2. Creating database management systems where we need to handle records with multiple fields.
  3. Writing system utilities for handling complex data structures like linked lists or trees.
  4. Debugging and analyzing memory usage in C programs by creating custom data structures to represent program states.

Prerequisites

To fully grasp this lesson, you should already have a good understanding of the following topics:

  1. Basic C syntax and control structures (if-else, for loops)
  2. Variables, data types, and operators
  3. Arrays in C programming
  4. Pointers in C programming
  5. Basic file I/O operations in C

Core Concept

In C, a struct is a user-defined data type that allows us to group multiple variables of different data types under a single name. To create a struct, we use the struct keyword followed by the struct name and an enclosed list of member variables. Here's a simple example:

struct Student {
int id;
char name[50];
float gpa;
};

In this example, we have defined a Student struct with three members: an integer id, a character array name to store the student's name, and a floating-point number gpa to represent their grade point average.

To create a variable of the Student type, we use the following syntax:

struct Student s1; // Declaring a struct variable

We can access each member of the struct using the dot operator (.). For example, to set the id, name, and gpa of the s1 student, we would write:

s1.id = 1;
strcpy(s1.name, "John Doe");
s1.gpa = 3.5;

To print the values of a struct variable, you can use the printf() function with the % formatting specifiers for each member type:

printf("Student ID: %d\n", s1.id);
printf("Student Name: %s\n", s1.name);
printf("Student GPA: %.2f\n", s1.gpa);

Worked Example

Let's create a simple program that reads information about students from the keyboard and stores it in an array of Student struct variables. We will then sort the students by their ID numbers and print the sorted list.

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

struct Student {
int id;
char name[50];
};

// Function to compare two student structs by their IDs
int compareStudents(const void *a, const void *b) {
return ((struct Student *) a)->id - ((struct Student *) b)->id;
}

int main() {
int numStudents;
printf("Enter the number of students: ");
scanf("%d", &numStudents);

struct Student students[numStudents]; // Declare an array of Student structs

for (int i = 0; i < numStudents; ++i) {
printf("\nEnter student %d's details:\n", i + 1);
printf("ID: ");
scanf("%d", &students[i].id);
printf("Name: ");
scanf("%49s", students[i].name);
}

qsort(students, numStudents, sizeof(struct Student), compareStudents); // Sort the students by ID

printf("\nSorted Students:\n");
for (int i = 0; i < numStudents; ++i) {
printf("\nStudent %d\nID: %d\nName: %s", i + 1, students[i].id, students[i].name);
}

return 0;
}

Common Mistakes

  1. Forgetting to include the required header files (e.g., stdio.h, string.h)
  2. Incorrectly defining struct members with incompatible data types or sizes
  3. Accessing out-of-bounds array indices when working with struct arrays
  4. Failing to use the dot operator (.) to access struct members correctly
  5. Forgetting to include the struct keyword when declaring a new variable of the custom type
  6. Using incorrect formatting specifiers when printing struct members with printf()
  7. Not defining a comparison function for sorting struct arrays in the correct format (i.e., returning 0 if the elements are equal and a positive or negative value depending on their order)

Practice Questions

  1. Create a Book struct that includes members for the book's title, author, publisher, publication year, and number of pages. Write a program to read information about several books and sort them by their publication years.
  2. Create a Point struct that includes members for x-coordinate and y-coordinate. Write a program to create an array of 10 points, calculate the total distance between all pairs of points using the Euclidean distance formula, and find the point with the maximum distance from the origin (0, 0).
  3. Create a Rectangle struct that includes members for the x-coordinate and y-coordinate of the top-left corner, width, and height. Write a program to create an array of rectangles, calculate their total area, and find the rectangle with the maximum area.

FAQ

  1. Can I nest structs in C? Yes, you can define one struct inside another by including the nested struct within the outer struct definition.
  2. How do I pass a struct to a function in C? To pass a struct to a function, simply declare the function's parameter as the same struct type. You can also pass pointers to struct variables for efficiency when dealing with large structures or multiple instances of the same structure.
  3. Can I use the sizeof operator on a struct variable in C? No, you should always use the sizeof operator with the struct type itself, not with a specific instance of the struct. This ensures that the size of the struct remains consistent across different compilers and platforms.
  4. What happens if I forget to include the semicolon at the end of a struct definition in C? Forgetting the semicolon will cause a syntax error, as the compiler expects a statement (i.e., a declaration or assignment) to end with a semicolon.
  5. How can I initialize a struct variable in C? To initialize a struct variable, you can either assign each member explicitly or use an initializer list enclosed in curly braces {}. For example:
struct Student s1 = { .id = 1, .name = "John Doe", .gpa = 3.5 };