Jacob Pollack
Jacob Pollack

Reputation: 3761

Pointer Arithmetic With Same Pointer (Array Subscript is not an Integer)

I just want to make sure my interpretation of what is going on here is correct. Consider the following snippet of code that is compiled on a 32-bit environment and declared on the stack.

// Declares an array of integers with a length of 10.
int arr[ 10 ] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

// Performs some pointer arithmetic.
int result = arr[ arr + 2 ];

Now I know that using the square braces in C is just an alias for the following.

*( ... )

So, following that aliasing, the snippet would translate to the following.

int result = *( arr + arr + 2 );

Now, my interpretation is that the pointer arithmetic will evaluate to the address of arr plus 2 multiplied by the size of an integer, plus the address of arr. Hence, my conclusion is that arr will point to memory I have not allocated. This will cause result to be some garbage value.

However, when I compile with both clang and gcc I receive an error saying "array subscript is not an integer". Why is this the case and where did my interpretation go wrong?

Upvotes: 2

Views: 593

Answers (2)

JackCColeman
JackCColeman

Reputation: 3807

Except for one letter your code should work!! The value within the [] needs to be an integer, so dereference arr+2 :

// Declares an array of integers with a length of 10.
int arr[ 10 ] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

// Performs some pointer arithmetic.
int result = arr[ *(arr + 2) ];

this should produce result = arr[2]; thus result = 2

I ran this on Eclipse/Microsoft C compiler and got exactly that result.

Finally, the convention of arr + 2 is discussed in K&R, there is ABSOLUTELY NOTHING wrong with what you were trying to do.

Just for fun try: int result = *(arr + *(arr + 2));

Upvotes: 0

Keith Thompson
Keith Thompson

Reputation: 263577

The array subscript is not an integer.

Pointer arithmetic is limited to:

  • pointer - pointer (yielding an integer)
  • pointer + integer (yielding a pointer)
  • pointer - integer (yielding a pointer).

You cannot add two pointer values, simply because there's no reasonable meaning for the result.

What did you expect arr[ arr + 2 ] to do? Update: I see you addressed that; you expected it to refer to some garbage address. This is a case where the language prevents you from generating garbage. Don't expect it to do that in all cases.

Upvotes: 8

Related Questions