An array is a data structure that can store a fixed-size sequential collection of elements of the same type. Declaring an array tells the compiler about the type of elements and the number of elements it will hold.
data_type array_name[array_size];
Example: int marks[5]; reserves space for 5 integer values.
A 1-dimensional array is the simplest form of an array where elements are stored linearly. Defining an array involves assigning initial values.
int numbers[5] = {10, 20, 30, 40, 50};Processing usually involves traversing the array using a loop to perform operations like reading, printing, or calculating sums.
for(int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
A 2-dimensional array is essentially an array of arrays, often visualized as a table with rows and columns.
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };Processing 2D arrays requires nested loops—the outer loop for rows and the inner loop for columns.
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
In C, you can pass an entire array to a function as a parameter. However, it is important to note that arrays are passed by reference (the address of the first element is passed).
void display(int arr[], int size) { ... }display(marks, 5);
Changes made to the array inside the function will affect the original array in the calling function.
C supports arrays with more than two dimensions. While 3D or higher arrays are possible, they are less common and more complex to manage in memory.
int survey[2][3][4];
This can be thought of as 2 blocks, each containing a 3x4 matrix.
void func(int arr[][3])).arr[5] in an array of size 5. This leads to garbage values or crashes.int a[5] = {1, 2};) fills the remaining spots with zero.&arr to a function instead of just arr when the function expects an array pointer.Q: Why are arrays passed by reference by default?
A: To save memory and time. Copying a large array would be inefficient.
Q: Can the size of an array be changed at runtime?
A: No, standard C arrays have a static size fixed at declaration. Dynamic allocation (malloc) is needed for flexible sizes.