In C, a struct (short for "structure") is a user-defined data type that allows grouping variables of different data types into a single unit. A struct can be thought of as a blueprint for creating objects that hold related data together.
struct structure_name {
data_type member1;
data_type member2;
...
data_type memberN;
};
struct: Keyword to define a structure.
structure_name: Name of the structure (optional, but usually given).
member1, member2, ..., memberN: Variables (or members) of the structure. Each can be of any data type, including other structs.
You can create a structure by using the struct keyword and declare each of its members inside curly braces:
struct MyStructure { // Structure declaration
int myNum; // Member (int variable)
char myLetter; // Member (char variable)
}; // End the structure with a semicolon
To access the structure, you must create a variable of it.
Use the struct keyword inside the main() method, followed by the name of the structure and then the name of the structure variable. To access members of a structure, use the dot syntax (.):
#include <stdio.h>
// Create a structure called myStructure
struct myStructure {
int myNum;
char myLetter;
};
int main() {
// Create a structure variable of myStructure called s1
struct myStructure s1;
// Assign values to members of s1
s1.myNum = 13;
s1.myLetter = 'B';
// Print values
printf("My number: %d\n", s1.myNum);
printf("My letter: %c\n", s1.myLetter);
return 0;
}
Now you can easily create multiple structure variables with different values, using just one structure:
// Create different struct variables
struct myStructure s1;
struct myStructure s2;
// Assign values to different struct variables
s1.myNum = 13;
s1.myLetter = 'B';
s2.myNum = 20;
s2.myLetter = 'C';
Remember that strings in C are actually an array of characters, and unfortunately, you can't assign a value to an array like this:
#include <stdio.h>
struct myStructure {
int myNum;
char myLetter;
char myString[30]; // String
};
int main() {
struct myStructure s1;
// Trying to assign a value to the string
s1.myString = "Some text";
// Trying to print the value
printf("My string: %s", s1.myString);
return 0;
}
An error will occur:
prog.c:12:15: error: assignment to expression with array type
However, there is a solution for this! You can use the strcpy() function and assign the value to s1.myString, like this:
#include <stdio.h>
#include <string.h>
struct myStructure {
int myNum;
char myLetter;
char myString[30]; // String
};
int main() {
struct myStructure s1;
// Assign a value to the string using the strcpy function
strcpy(s1.myString, "Some text");
// Print the value
printf("My string: %s", s1.myString);
return 0;
}
Result:
My string: Some text
You can also assign values to members of a structure variable at declaration time, in a single line.
Just insert the values in a comma-separated list inside curly braces {}. Note that you don't have to use the strcpy() function for string values with this technique:
#include <stdio.h>
struct myStructure {
int myNum;
char myLetter;
char myString[30];
};
int main() {
// Create a structure variable and assign values to it
struct myStructure s1 = {13, 'B', "Some text"};
// Print values
printf("%d %c %s", s1.myNum, s1.myLetter, s1.myString);
return 0;
}
Modifying values in a structure
If you want to change/modify a value, you can use the dot syntax (.).
And to modify a string value, the strcpy() function is useful again.
Example:
#include <stdio.h>
#include <string.h>
// Define the structure
struct Book {
char title[100];
char author[50];
int pages;
float price;
};
int main() {
// Declare and initialize a structure variable
struct Book book1;
// Assign initial values to the structure members
strcpy(book1.title, "C Programming Language");
strcpy(book1.author, "Brian W. Kernighan");
book1.pages = 275;
book1.price = 30.50;
// Display the initial values
printf("Initial Book Details:\n");
printf("Title: %s\n", book1.title);
printf("Author: %s\n", book1.author);
printf("Pages: %d\n", book1.pages);
printf("Price: $%.2f\n", book1.price);
// Modify the values of the structure members
strcpy(book1.title, "The C Programming Language, 2nd Edition");
book1.pages = 300;
book1.price = 35.99;
// Display the modified values
printf("\nModified Book Details:\n");
printf("Title: %s\n", book1.title);
printf("Author: %s\n", book1.author); // Author remains the same
printf("Pages: %d\n", book1.pages);
printf("Price: $%.2f\n", book1.price);
return 0;
}
Nested Structures
Nested structures in C allow you to define a structure within another structure, enabling the organization of complex data types. This is particularly useful when you want to group related data together in a hierarchical manner.
Let’s create an example that demonstrates how to use nested structures in C. In this case, we will define a structure to represent an employee, which includes their personal information and their address as a nested structure.
#include <stdio.h>
#include <string.h>
// Define the Address structure
struct Address {
char street[100];
char city[50];
int zip;
};
// Define the Employee structure
struct Employee {
int id;
char name[50];
struct Address address; // Nested structure
};
int main() {
// Create an instance of Employee
struct Employee emp;
// Assign values to the Employee structure
emp.id = 101;
strcpy(emp.name, "John Doe");
// Assign values to the nested Address structure
strcpy(emp.address.street, "123 Elm St");
strcpy(emp.address.city, "Springfield");
emp.address.zip = 12345;
// Print the Employee details
printf("Employee ID: %d\n", emp.id);
printf("Employee Name: %s\n", emp.name);
printf("Address: %s, %s, %d\n", emp.address.street, emp.address.city, emp.address.zip);
return 0;
}
Structure Definitions:
The Address structure is defined with three members: street, city, and zip.
The Employee structure is defined with three members: id, name, and a nested structure address of type struct Address.
Creating an Instance:
An instance of Employee named emp is created.
Assigning Values:
The id and name members of the emp instance are assigned values directly.
For the nested address structure, values are assigned using the dot operator. For example, emp.address.street accesses the street member of the nested address structure.
Printing Values:
The details of the employee, including the nested address information, are printed using printf().
When you run the program, the output will be:
Employee ID: 101
Employee Name: John Doe
Address: 123 Elm St, Springfield, 12345
Nested structures in C provide a powerful way to organize related data hierarchically. By embedding one structure within another, you can create complex data types that reflect real-world relationships, making your code more intuitive and manageable.
Structure Pointer
A structure pointer in C is a pointer that holds the address of a structure variable, allowing for indirect access to the structure's members. This feature is particularly useful for managing dynamic data structures and passing structures to functions efficiently.
To declare a structure pointer, you use the following syntax:
struct StructureName *pointerName;
For example, if you have a structure defined as follows:
struct Student {
int roll_no;
char name[50];
};
You can declare a pointer to this structure:
struct Student *ptr;
Before using a structure pointer, it must be initialized to point to a valid structure variable. You can do this using the address-of operator (&):
struct Student s1;
ptr = &s1; // ptr now points to s1
You can access the members of a structure through a pointer using two methods:
Using the arrow operator (->):
ptr->roll_no = 27; // Assigning value to roll_no
strcpy(ptr->name, "John Doe"); // Assigning value to name
Using the dereference operator (*) and dot operator (.):
(*ptr).roll_no = 27; // Assigning value to roll_no
strcpy((*ptr).name, "John Doe"); // Assigning value to name
Here’s a complete example demonstrating the use of structure pointers:
#include <stdio.h>
#include <string.h>
struct Student {
int roll_no;
char name[50];
};
int main() {
struct Student s1; // Create a structure variable
struct Student *ptr = &s1; // Create a pointer to the structure
// Accessing structure members using the pointer
ptr->roll_no = 27;
strcpy(ptr->name, "John Doe");
// Displaying the values
printf("Roll Number: %d\n", ptr->roll_no);
printf("Name: %s\n", ptr->name);
return 0;
}
When working with structures, especially when the number of instances (or records) is not known beforehand, malloc() allows you to allocate memory dynamically. This helps in managing memory efficiently and avoiding stack overflow issues that can occur with large data sets.
Define the Structure: First, you define the structure that you want to use.
Declare a Pointer: Declare a pointer of the structure type.
Allocate Memory: Use malloc() to allocate memory for the structure.
Access Members: Use the pointer to access the structure members.
Free Memory: Once done, use free() to release the allocated memory.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Define a structure
struct Person {
char name[50];
int age;
float height;
};
int main() {
int numPersons;
// Ask the user for the number of persons
printf("Enter the number of persons: ");
scanf("%d", &numPersons);
// Allocate memory for an array of Person structures
struct Person *persons = (struct Person *)malloc(numPersons * sizeof(struct Person));
// Check if malloc succeeded
if (persons == NULL) {
printf("Memory allocation failed!\n");
return 1; // Exit if memory allocation fails
}
// Loop to assign values to each person's structure
for (int i = 0; i < numPersons; i++) {
printf("Enter details for person %d:\n", i + 1);
printf("Name: ");
scanf("%s", persons[i].name); // Using %s for string input
printf("Age: ");
scanf("%d", &persons[i].age);
printf("Height: ");
scanf("%f", &persons[i].height);
}
// Print the values of all persons
printf("\nDetails of persons:\n");
for (int i = 0; i < numPersons; i++) {
printf("Person %d:\n", i + 1);
printf("Name: %s\n", persons[i].name);
printf("Age: %d\n", persons[i].age);
printf("Height: %.1f\n", persons[i].height);
printf("\n");
}
// Free the allocated memory
free(persons);
return 0;
}
Typedef with Structures
The typedef keyword in C is used to create aliases for existing data types, including structures. This can simplify code and improve readability by allowing you to use shorter or more meaningful names for complex types. Below is a detailed explanation of how to use typedef with structures, along with examples.
The syntax for using typedef with a structure is as follows:
typedef struct StructureName {
data_type member1;
data_type member2;
// ...
} AliasName;
After this declaration, you can use AliasName to declare variables of that structure type without needing to use the struct keyword each time.
Here’s an example that demonstrates how to define a structure for a student and use typedef to create an alias for it:
#include <stdio.h>
#include <string.h>
// Define the structure and create a typedef alias
typedef struct {
char name[50];
int age;
float gpa;
} Student;
int main() {
// Declare a variable of type Student
Student student1;
// Assign values to the structure members
strcpy(student1.name, "Alice");
student1.age = 20;
student1.gpa = 3.8;
// Print the student information
printf("Student Name: %s\n", student1.name);
printf("Student Age: %d\n", student1.age);
printf("Student GPA: %.2f\n", student1.gpa);
return 0;
}
Structure Definition: The structure is defined with three members: name, age, and gpa. The typedef creates an alias called Student, allowing you to use this name instead of struct every time you declare a variable.
Variable Declaration: In the main() function, a variable student1 of type Student is declared.
Assigning Values: Values are assigned to the members of the student1 structure using the dot operator.
Printing Values: The program prints the details of the student.
When you run the above program, the output will be:
Student Name: Alice
Student Age: 20
Student GPA: 3.80
Simplifies Code: Reduces the need to repeatedly use the struct keyword, making the code cleaner and easier to read.
Improves Readability: Using meaningful names for types can help clarify the purpose of variables.
Eases Maintenance: If the structure definition changes, you only need to update the typedef declaration.
While structures are powerful, they do have limitations:
No Member Functions: Unlike classes in C++, structures cannot contain functions.
No Data Hiding: All members of a structure are public and can be accessed from anywhere in the code.
Memory Consumption: Structures can lead to increased memory usage due to padding for alignment.
No Static Members: Structures cannot have static members or constructors
Structures in C provide a flexible way to group related data of different types, making it easier to manage complex data sets. They are widely used in various applications, from simple data management to complex data structures like linked lists and trees. Understanding how to define, declare, and manipulate structures is essential for effective programming in C.