C Structures
Learn C through interactive, bite-sized lessons. Master the fundamentals of programming and systems development.
Start C Journey →C structures are user-defined data types that allow programmers to group related variables of different data types under a single name. They provide a way to organize and manage complex data efficiently.
Defining a Structure
To define a structure in C, use the struct keyword followed by the structure name and a block containing member variables:
struct Person {
char name[50];
int age;
float height;
};
Declaring Structure Variables
Once defined, you can declare variables of the structure type:
struct Person person1, person2;
Alternatively, you can combine the definition and declaration:
struct Person {
char name[50];
int age;
float height;
} person1, person2;
Accessing Structure Members
Use the dot (.) operator to access individual members of a structure:
strcpy(person1.name, "John Doe");
person1.age = 30;
person1.height = 1.75;
Initializing Structures
You can initialize a structure at declaration time:
struct Person person3 = {"Jane Smith", 25, 1.68};
Structures and Functions
Structures can be passed to functions as arguments or returned from functions. This allows for modular and organized code:
void printPerson(struct Person p) {
printf("Name: %s\nAge: %d\nHeight: %.2f\n", p.name, p.age, p.height);
}
// Usage
printPerson(person1);
Nested Structures
Structures can contain other structures as members, allowing for more complex data organization. For more information on this topic, see C Nested Structures.
Pointers to Structures
You can create pointers to structures, which is useful for dynamic memory allocation and efficient function parameter passing:
struct Person *personPtr = &person1;
printf("Name: %s\n", personPtr->name); // Use -> operator with pointers
Important Considerations
- Structures are passed by value to functions by default, which can be inefficient for large structures. Consider using pointers or references instead.
- Memory alignment may cause padding between structure members, affecting the total size of the structure.
- When using structures with dynamic memory allocation, remember to free all allocated memory to prevent memory leaks.
Applications of Structures
Structures are widely used in C programming for various purposes:
- Representing complex data types (e.g., date, time, geometric shapes)
- Implementing abstract data types like linked lists, trees, and graphs
- Organizing related data in databases or file I/O operations
- Creating custom data structures for specific application needs
By mastering C structures, you'll be able to write more organized and efficient code, especially when dealing with complex data relationships. For more advanced usage, consider exploring C Unions and C Typedef to further enhance your data structuring capabilities.