1

I find a piece of C++ code in textbook and have some questions.:

int ia[10]; // an integer array with 10 elements
int *ptr = ia; //the address of the first element in array. 
int *end = &ia[10]; //
while ( ptr != end ){
    std::cout<<*(ptr++)<<" ";
}
std::cout<<std::endl;

Since, the boundary of this array is from 0 to 9, which means that the ia[10] is out of boundary. Why it is allowed in C and C++?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
allen.lao
  • 49
  • 2
  • 7

1 Answers1

1

end is pointing to the address immediately after the 10 elements of ia. The while loop is then looking to see when ptr, which is a pointer stepping along the array, reaches the address immediately after the array ia and thus the loop terminates. In this way there is no attempt to output any values beyond the initial ia array.

The key is that C uses references to memory locations.

Chapter 2 of this will give more info: http://pdos.csail.mit.edu/6.828/2012/readings/pointers.pdf

Gavin
  • 460
  • 4
  • 11