Struct Definition and Usage
Struct Definition and Usage
Struct Declaration
In C, a struct is a user-defined data type that groups variables of different types into a single unit. To declare a struct, you use the struct keyword followed by a struct name and a list of member variables.
struct Person {
char name[50];
int age;
};
Struct Members
A struct can contain multiple members, each of which can be of any valid C data type. Members are accessed using the dot operator (.).
struct Person person;
person.name = "Alice";
person.age = 25;
Struct Usage
Structs are commonly used to create custom data types for complex data representations. They can be initialized and used in memory, and their members can be accessed or modified individually.
Creating Instances
To create an instance of a struct, you allocate memory using malloc or sizeof and assign values to its members.
struct Person* personPtr = malloc(sizeof(struct Person));
personPtr->name = "Bob";
personPtr->age = 30;
Accessing Members
Members of a struct can be accessed using the dot operator. This allows individual variables to be read or written.
printf("Name: %s, Age: %d\n", person.name, person.age);
Nested Structures
Structs can contain other structs, enabling hierarchical data organization.
struct Address {
char street[50];
char city[30];
};
Best Practices
- Memory Management: Always allocate and deallocate memory properly to avoid leaks.
- Data Integrity: Ensure that member variables are initialized correctly to prevent undefined behavior.
- Clarity: Use meaningful names for struct members to improve code readability.
Example: Struct in Practice
Here’s an example of a struct representing a student:
struct Student {
char name[50];
int rollNumber;
float gpa;
};
struct Student student1;
student1.name = "Alice";
student1.rollNumber = 101;
student1.gpa = 3.8;
This struct can be used to store and manipulate student data efficiently.