In C programming, the error “array subscript is not an integer” occurs when you try to use a non-integer value as an index for an array. Array indices must be integers, as they represent positions within the array. This error is significant because it prevents the code from compiling, ensuring that only valid indices are used to access array elements.
In C, array subscripts (or indices) are used to access elements within an array. They must be integer values. This means you can use:
0
, 1
, 2
, etc.int i = 3; array[i];
array[2 + 3];
The subscript value must be within the valid range of the array, starting from 0
up to SIZE-1
, where SIZE
is the total number of elements in the array.
Here are common scenarios that lead to the ‘array subscript is not an integer’ error in C:
Using Non-Integer Types as Index:
float index = 2.5; array[index] = 10;
Incorrect Pointer Arithmetic:
int *ptr1, *ptr2; array[ptr1 + ptr2] = 10;
Using Structs or Other Non-Integer Types:
struct Point { int x, y; }; struct Point p; array[p] = 10;
Using Strings as Index:
char *str = "hello"; array[str] = 10;
Function Calls Returning Non-Integer Types:
float getIndex() { return 2.5; } array[getIndex()] = 10;
These scenarios typically arise from misunderstandings about valid array indexing in C.
// Example 1: Using a float as an array subscript
int arr[5] = {1, 2, 3, 4, 5};
float index = 2.5;
int value = arr[index]; // Error: Array subscript is not an integer
// Example 2: Using a string as an array subscript
int numbers[3] = {10, 20, 30};
char *str = "1";
int result = numbers[str]; // Error: Array subscript is not an integer
// Example 3: Using a character as an array subscript
char letters[4] = {'a', 'b', 'c', 'd'};
char ch = '2';
char letter = letters[ch]; // Error: Array subscript is not an integer
// Example 4: Missing or incorrect indexing syntax
char alphabets[] = {'a', 'b', 'c'};
char result = alphabets(1); // Error: Array subscript is not an integer
Ensure Integer Indexing:
int arr[] = {1, 2, 3, 4, 5};
int index = 2;
int value = arr[index]; // Correct
float index = 2.5;
int value = arr[index]; // Incorrect
Type Casting:
static_cast
for enums or other types:enum MyEnum { A, B, C };
MyEnum e = A;
int value = arr[static_cast<int>(e)]; // Correct
Avoid Pointer Arithmetic Errors:
int *ptr = arr;
int value = *(ptr + 2); // Correct
int *ptr1 = arr;
int *ptr2 = arr + 2;
int value = ptr1 + ptr2; // Incorrect
Check Index Bounds:
if (index >= 0 && index < sizeof(arr)/sizeof(arr[0])) {
int value = arr[index]; // Safe access
}
Use Functions Correctly:
void func(int arr[]) {
puts(arr); // Correct
}
By following these practices, you can prevent and resolve the ‘array subscript is not an integer’ error effectively.
Follow these key points:
arr[index]
.+
and dereferencing with *
.By following these practices, you can effectively resolve the ‘array subscript is not an integer’ error in C.