Structure vs Array in C: Key Differences and Usage
structure groups different types of variables under one name, while an array stores multiple elements of the same type in a sequence. Structures allow mixed data types and named fields, whereas arrays provide indexed access to homogeneous data.Quick Comparison
This table summarizes the main differences between structures and arrays in C.
| Factor | Structure | Array |
|---|---|---|
| Data Types | Can hold different types together | Holds only one type of elements |
| Access Method | Access by field names | Access by index numbers |
| Memory Layout | Fields stored sequentially but can have padding | Elements stored contiguously without gaps |
| Size | Size depends on all fields combined | Size = element size × number of elements |
| Use Case | Group related but different data | Store list of similar items |
| Declaration | Uses struct keyword | Uses type with square brackets |
Key Differences
Structures in C let you combine variables of different types into one unit. For example, you can store an integer, a float, and a character array together in one struct. This is useful when you want to represent a complex object like a person with a name, age, and height.
On the other hand, arrays hold multiple values of the same type in a fixed-size sequence. You access each element by its index number, starting from zero. Arrays are ideal when you need to store many items of the same kind, like a list of scores or temperatures.
Memory-wise, arrays store elements one after another without gaps, making them efficient for looping and indexing. Structures may have padding bytes between fields to align data properly, which can affect their size. Also, structures use named fields for clarity, while arrays rely on numeric indexes.
Code Comparison
Here is an example showing how to store and print a person's data using a structure in C.
#include <stdio.h>
struct Person {
char name[20];
int age;
float height;
};
int main() {
struct Person p1 = {"Alice", 30, 5.5f};
printf("Name: %s\n", p1.name);
printf("Age: %d\n", p1.age);
printf("Height: %.1f\n", p1.height);
return 0;
}Array Equivalent
To store similar data using arrays, you would need separate arrays for each field and use the same index to access related data.
#include <stdio.h> int main() { char names[1][20] = {"Alice"}; int ages[1] = {30}; float heights[1] = {5.5f}; printf("Name: %s\n", names[0]); printf("Age: %d\n", ages[0]); printf("Height: %.1f\n", heights[0]); return 0; }
When to Use Which
Choose structures when you need to group different types of related data into one object for clarity and easier management. They are perfect for representing real-world entities with multiple attributes.
Choose arrays when you need to store many items of the same type and access them by position, such as lists or sequences. Arrays are simpler and more efficient for homogeneous data.