What is an Array Subscript in C?
An array subscript is an index used to access a specific element within an array. In C, array indexing starts at 0, meaning the first element is accessed with index 0, the second with index 1, and so on. The syntax for accessing an array element is:
array_name[index];
For example:
int numbers[5] = {10, 20, 30, 40, 50}; printf("%d", numbers[2]); // Outputs: 30
Here, numbers[2] accesses the third element of the array.
Understanding Memory and Subscript
Each element in an array is stored in continuous memory. The subscript acts as an offset from the base address.
If numbers is the base address, then:
- numbers[0] points to numbers + 0
- numbers[1] points to numbers + 1
- …
- This is why array indexing is efficient in C
Accessing and Modifying Elements Using Subscript
Arrays in C are declared by specifying the data type, array name, and the number of elements:
int numbers[5];
You can also initialize it at the time of declaration:
int numbers[5] = {10, 20, 30, 40, 50};
To access elements, use subscripts:
printf("%d", numbers[0]); // Outputs: 10
To modify an element:
numbers[1] = 25; // Changes the second element to 25
The Relationship Between Arrays and Pointers
In C, arrays and pointers are closely related. The array name can be considered as a pointer to the first element. Thus, the expression array[i] is equivalent to *(array + i). This means:
int numbers[5] = {10, 20, 30, 40, 50}; printf("%d", *(numbers + 2)); // Outputs: 30
Interestingly, due to this equivalence, 2[numbers] is also valid and yields the same result as numbers[2].
Multidimensional Arrays
C supports multidimensional arrays, such as two-dimensional arrays:
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
Accessing elements in a multidimensional array uses multiple subscripts:
printf("%d", matrix[1][2]); // Outputs: 6
Here, matrix[1][2] accesses the element in the second row and third column.
Common Errors with Array Subscripts
1. Out-of-Bounds Access
C does not check array bounds at compile-time or runtime. Accessing outside the array size leads to undefined behavior:
int arr[3] = {1, 2, 3}; printf("%d", arr[5]); // Wrong! May crash or show garbage
2. Using Negative Index
C does not support negative subscripts:
int arr[4] = {1, 2, 3, 4}; printf("%d", arr[-1]); // Undefined behavior
3. Non-Integer Subscripts
Array subscripts must be integers. You can’t use float or char as indices:
float index = 1.5; printf("%d", arr[index]); // Error!
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Practice BCA MCQs
- Practice Computer Science MCQs
- Apply for Computer Science Internship
- Watch Advanced C Programming Videos
- Check Computer Science Books