question of pass the end pointer

1
2
3
4
5
6
7
8
9
int main()
{
  int a[5] = {0, 1, 2, 3, 4};
  int const *aPtr = a;
  aPtr += 5; //save and reliable  
  //what if
  aPtr = a;
  aPtr -= 1; //?
}


Thanks
Last edited on
You are now pointing at the memory 1 int size before where your array is stored. This could be anything, possibly not even memory your program is allowed to access.

You should note, however, that adding 5 to your pointer will have the same issue as you are now pointing beyond the end of your array.
about the first situationaPtr += 5
it is save and well-defined even it point to the address I don't know(as long as I don't access it)
but the second situationaPtr -= 1
I can't find any book say anything about it
I don't know is it save or not even I didn't try to access the address point by the pointer
Neither are technically "safe", as both will be pointing to memory you don't own. Though if you don't ever access it, I suppose you could call it "safe". The first will simply be at undefined memory after your array, and the second will be at undefined memory before it. Just like any pointer, you can set it to whatever you like and it won't actually create a problem unless you try to write to it.

Trying to access either could do anything.

Assume your array a is stored at memory location 1000.
a + 5 will be at memory location 1000 + 5*sizeof(int).
a - 1 will be at memory location 1000 - sizeof(int).
Topic archived. No new replies allowed.