Back to C Programming
2026-04-305 min read

15.13 Structure Assignment

Learn 15.13 Structure Assignment step by step with clear examples and exercises.

Title: Mastering Structure Assignments in C Programming

Why This Matters

Understanding structure assignments is crucial for managing complex data structures in C programming. This concept is essential for handling real-world problems, coding interviews, and debugging common issues. By using structures, developers can create custom data types that better represent the problem domain, making code more readable and maintainable. Structures allow for efficient organization of related data, improving program efficiency and reducing errors.

In addition to these benefits, structure assignments enable effective handling of data records, such as student information or employee details, which often involve multiple fields of different data types. This makes structures an indispensable tool in C programming.

Prerequisites

Before diving into structure assignments, you should be familiar with:

  1. Basic C syntax and variables
  2. Arrays and pointers
  3. Data types and operators
  4. Functions and function prototypes
  5. Understanding memory management concepts such as dynamic memory allocation (malloc) and freeing memory.
  6. Having a good grasp of control structures like loops and conditional statements.
  7. Familiarity with file input/output using fopen, fread, fwrite, and fclose.
  8. Understanding the difference between value types and reference types, as well as pointers to structures.
  9. Knowledge of basic data structures like arrays and linked lists.
  10. Familiarity with structure declarations and accessing structure members.

Core Concept

In C programming, structures are user-defined data types that allow combining different data types into a single variable. Structures can help manage complex data such as records, where each record has multiple fields of different data types.

Here's an example of a simple structure definition:

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

In this example, we define a Student structure with three fields: name, age, and gpa. Each field has its respective data type. To access the fields of a structure, you use the dot operator (.). For instance, to store a student's name, age, and GPA in a variable called student, you would do:

struct Student student;
strcpy(student.name, "John Doe");
student.age = 20;
student.gpa = 3.5;

Structure Initialization and Assignment

You can initialize a structure variable when you declare it:

struct Student student = {"John Doe", 20, 3.5};

Structure variables can also be assigned using the assignment operator (=). However, this only works if both structures have the same fields and compatible data types.

struct Student student1 = {"John Doe", 20, 3.5};
struct Student student2;
student2 = student1; // This is copying the entire structure, not just a reference.

Structure Pointers and Dynamic Memory Allocation

Structure pointers allow for dynamic memory allocation of structures. To dynamically allocate memory for a structure, use malloc().

struct Student *student = (struct Student *) malloc(sizeof(struct Student));

To free the allocated memory, use free().

free(student);

Structure Array Operations

You can declare an array of structures and access its elements using subscripting.

struct Student students[3];
students[0] = student1; // Assigning a structure to an array element.

Worked Example

Let's create a simple program that reads student records from a file named "students.txt" and displays the details of each student. Assume that the file contains one record per line in the following format: name age gpa.

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

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

int main() {
FILE *file = fopen("students.txt", "r");

if (file == NULL) {
printf("Error: Unable to open the file.\n");
return 1;
}

struct Student students[100];
int count = 0;

while (!feof(file)) {
fscanf(file, "%s %d %.2f", students[count].name, &students[count].age, &students[count].gpa);
count++;
}

fclose(file);

printf("\nStudent Records:\n");
for (int i = 0; i < count; i++) {
printf("\nName: %s\nAge: %d\nGPA: %.2f", students[i].name, students[i].age, students[i].gpa);
}

return 0;
}

Common Mistakes

  1. Forgetting to include the necessary header files (stdio.h and string.h)
  2. Not initializing structure variables before using them
  3. Accessing out-of-bounds array elements within a structure
  4. Using incorrect data types for structure fields
  5. Forgetting semicolons at the end of statements
  6. Trying to compare structures directly with the equal (==) operator instead of looping through each field and comparing them individually.
  7. Not properly allocating and freeing memory when using dynamic memory allocation within structures.
  8. Failing to check for errors when reading or writing files containing structure data.
  9. Not handling edge cases, such as empty lines or improperly formatted records in the input file.
  10. Forgetting to declare function prototypes before their usage.

Common Mistakes - Structure Pointers and Dynamic Memory Allocation

  1. Failing to cast the returned value from malloc() to the appropriate structure type.
  2. Not freeing memory allocated for a structure when it is no longer needed, leading to memory leaks.
  3. Using free() on a null pointer or an already-freed pointer, which can cause undefined behavior.
  4. Allocating insufficient memory for a structure, leading to segmentation faults or other runtime errors.
  5. Forgetting to check the return value of malloc() and handling allocation failures appropriately.

Practice Questions

Question 1:

Write a C program that creates a Student structure with fields for name, age, and GPA. The program should read student records from a file named "students.txt" and display the details of each student. Assume that the file contains one record per line in the following format: name age gpa.

Question 2:

Modify the previous program to handle empty lines or improperly formatted records in the input file. Display an error message for any invalid records and continue processing the remaining valid records.

FAQ

How can I declare a structure with variable-length arrays?

To declare a structure with a variable-length array, you can use a flexible array member (FAM). In C99 and later versions, you can define a structure like this:

struct Student {
char name[1]; // Note the empty size specifier for the flexible array member.
int age;
float gpa;
};

The name field will now be treated as an array with a variable length, and you can allocate memory to it dynamically using malloc().

How do I compare two structures in C?

To compare two structures in C, you should loop through each field and compare them individually. Here's an example:

struct Student s1 = {"John Doe", 20, 3.5};
struct Student s2 = {"Jane Smith", 21, 3.6};

if (strcmp(s1.name, s2.name) == 0 && s1.age == s2.age && fabs(s1.gpa - s2.gpa) < EPSILON) {
printf("The structures are equal.\n");
} else {
printf("The structures are not equal.\n");
}

In this example, EPSILON is a small positive number used to account for floating-point inaccuracies.