Difference Between Structure and Array in C
In C programming, both arrays and structures are used to store collections of data. However, they serve different purposes and have distinct characteristics.
Understanding the differences between structures and arrays is essential for designing efficient programs and choosing the appropriate data storage method.
1. Array
An array is a collection of elements of the same data type stored in contiguous memory locations. Arrays allow easy access to multiple values using a single variable name with an index.
Example of an array:
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
for(int i = 0; i < 5; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
return 0;
}
2. Structure
A structure in C is a user-defined data type that allows grouping variables of different types under a single name. Structures are used to represent complex data with multiple attributes.
Example of a structure:
#include <stdio.h>
struct Student {
int id;
char name[50];
float marks;
};
int main() {
struct Student s1 = {101, "John", 85.5};
printf("ID: %d\nName: %s\nMarks: %.2f\n", s1.id, s1.name, s1.marks);
return 0;
}
3. Key Differences Between Structure and Array
- Data Type: All elements in an array must be of the same type; a structure can have variables of different types.
- Memory Allocation: Arrays store elements in contiguous memory; structures may contain elements that require different sizes.
- Access: Array elements are accessed using an index; structure members are accessed using the dot (.) operator.
- Purpose: Arrays are used to store homogeneous data; structures are used to represent complex entities with heterogeneous data.
- Flexibility: Structures are more flexible as they can hold multiple data types; arrays are simpler but limited to one type.
4. Example Comparison
Array Example:
int marks[3] = {85, 90, 95};
printf("First student marks = %d", marks[0]);
Structure Example:
struct Student {
int id;
char name[20];
float marks;
};
struct Student s1 = {101, "Alice", 92.5};
printf("Student name = %s", s1.name);
Notes
- Use arrays when you need to store multiple values of the same type for easy iteration and indexing.
- Use structures when you need to store multiple attributes of different types together to model real-world entities.
- Arrays can be combined with structures (e.g., array of structures) for more advanced data storage.
Conclusion
Arrays and structures are fundamental in C, but they serve different purposes. Arrays are ideal for homogeneous data collections, while structures allow heterogeneous grouping of variables. Understanding these differences helps in designing efficient and organized C programs.
Codecrown