📜  c struct array (1)

📅  最后修改于: 2023-12-03 14:59:37.851000             🧑  作者: Mango

C Struct Array

In C programming language, a struct is a user-defined data type that allows you to combine multiple variables of different types into a single unit. Arrays, on the other hand, are collections of similar data items stored in contiguous memory locations. Combining structs with arrays enables you to create a collection of structured data.

Declaration and Initialization

To declare an array of structs in C, you need to define the struct type first. Here's an example:

struct Employee {
    char name[50];
    int age;
    float salary;
};

struct Employee employees[100];  // Array of structs

In this example, we define a struct type Employee that contains three members (name, age, and salary). Then, we declare an array employees of type Employee with a size of 100, which means it can store up to 100 Employee structs.

Accessing Struct Array Elements

You can access individual elements of a struct array using the index notation. For example:

employees[0].age = 25;
strcpy(employees[0].name, "John Doe");
employees[0].salary = 5000.0;

In this code snippet, we assign values to the members of the first element in the employees array.

Iterating Over a Struct Array

To iterate over a struct array, you can use a loop such as a for loop. Here's an example code that prints the details of all employees:

for (int i = 0; i < 100; i++) {
    printf("Employee %d:\n", i+1);
    printf("Name: %s\n", employees[i].name);
    printf("Age: %d\n", employees[i].age);
    printf("Salary: %.2f\n", employees[i].salary);
}
Dynamic Memory Allocation

In some cases, you may not know the size of the struct array at compile-time. In such situations, you can use dynamic memory allocation functions like malloc() to allocate memory for the array. Here's an example:

int n;
printf("Enter the number of employees: ");
scanf("%d", &n);

struct Employee* employees = (struct Employee*)malloc(n * sizeof(struct Employee));

In this code snippet, the user specifies the number of employees, and we dynamically allocate memory for the array using malloc().

Freeing Memory

If you allocate memory dynamically, it's important to free the memory once you are done using it to avoid memory leaks. In the case of a struct array, you can use the free() function to release the memory, as shown below:

free(employees);

Make sure to call free() only when you are done using the struct array.

Conclusion

Using a struct array in C allows you to store and process collections of structured data. With the flexibility of dynamic memory allocation, you can create struct arrays of any size according to your program's requirements. Understanding and utilizing struct arrays in C will help you build complex data structures and efficiently manage related data.