-3

For the below code snippet , what type of rvalue is returned by expression array+1 and &array+1 ?

int main()
{
int array[2][3];
printf("%p  %p ", array+1, &array+1);
return 0;
}

I have already gone through below link but still my doubt is not cleared .

2D array variable pointer confusion

1
  • array evaluate => int(*)[3] so +1 corresponds to the movement of int[3] (as 3*sizeof(int)). &array evaluate => int(*)[2][3] so +1 corresponds to the movement of int[2][3] (as 6*sizeof(int)). Commented Apr 4, 2017 at 13:34

1 Answer 1

2
  • When array is used in an expression, it "decays" to a pointer of the first element.
  • The first element of a 2D array int[2][3] is a 1D array int[3].
  • Therefore the expression array+1 gives a pointer to such a 1D array.
  • The expression array+1 has type int(*)[3], an array pointer to an array of 3 integers.
  • When you do + 1 on any pointer, pointer arithmetic is invoked and you get "plus one pointed-at object", rather than "plus one byte/address".
  • Thus array+1 gives the second array of type int[3] in your 2D array.

  • &array is different, it gives a pointer to the address of the array itself. A pointer to a 2D array, type int(*)[2][3].
  • If you do &array + 1 you therefore do pointer arithmetic on objects that are 2D arrays and end up pointing "one 2D array outside the allocated array", which probably isn't meaningful.
Sign up to request clarification or add additional context in comments.

7 Comments

I can't help but wonder about the last bullet. Computing the address of one past the end of an array is explicitly okay by the standard. But is a single variable considered an "array of 1" for &var + 1 to be well defined?
@StoryTeller You can point one past the end of the array, but you may not de-reference the object there. As far as I know, the "one past the end" is allowed just to make constructs like this possible: start=list; end=list+list.size(); for(i=start; i!=end; i++) { ...
I know it's allowed and I know why (I do believe my comment starts with that). But while it may hold for int a[1]; that calculating a + 1 is okay, I'm not so certain it will be okay for int a; to calculate &a + 1. This is a pure language lawyer pondering.
@StoryTeller It is the same. 6.5.6/7 "For the purposes of these operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type."
@stackuser The address of the 2D array is obviously the same as the address of the first 1D array in that 2D array. But if you do pointer arithmetic on them, you'll get different results, as explained in the answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.