Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Difference between Structure and Array in C
In C, both structures and arrays are used as containers to store data. The key difference is that a structure can hold variables of different data types, while an array can only hold variables of the same data type.
Example
The following example demonstrates the difference between a structure and an array in C ?
#include <stdio.h>
// Structure: holds different data types
struct Student {
char name[20];
int age;
float gpa;
};
int main() {
// Structure usage
struct Student s1 = {"Alice", 20, 3.85};
printf("Structure:
");
printf(" Name: %s
", s1.name); // access by member name
printf(" Age: %d
", s1.age);
printf(" GPA: %.2f
", s1.gpa);
// Array usage: holds same data type only
int scores[] = {85, 92, 78, 95, 88};
printf("\nArray:
");
int i;
for (i = 0; i < 5; i++) {
printf(" scores[%d] = %d
", i, scores[i]); // access by index
}
return 0;
}
The output of the above code is ?
Structure: Name: Alice Age: 20 GPA: 3.85 Array: scores[0] = 85 scores[1] = 92 scores[2] = 78 scores[3] = 95 scores[4] = 88
Key Differences
| Feature | Structure | Array |
|---|---|---|
| Data Types | Multiple different types (int, char, float, etc.) | Same type only |
| Memory Layout | May have padding (not necessarily contiguous) | Contiguous memory blocks |
| Element Access | By member name (s1.name) |
By index (arr[0]) |
| Internal Pointer | No internal pointer concept | Array name acts as pointer to first element |
| Declaration | Object can be created after struct definition |
Must be declared with size or initializer |
| Performance | Slower access (member lookup) | Faster access (direct index calculation) |
| Keyword | struct |
Type followed by []
|
Conclusion
Use a structure when you need to group related data of different types (like a student record with name, age, and GPA). Use an array when you need to store multiple values of the same type (like a list of scores) with fast index-based access.
Advertisements
