Short Pointer Problem

As I know the initialize of the array[5]={11,12,13} are 11,12,13,0,0.

There is no array[-3],array[-2],array[-1], therefore they should be -xxxxx.(some unknown)

Then, I get the answer:
array[-3],array[-2],array[-1],array[0],array[1],array[2],array[3].
-xxxxx, -xxxxx, -xxxxx, 11, 12, 13, 0.

But the compiler show the answer is :
array[-3],array[-2],array[-1],array[0],array[1],array[2],array[3].
-xxxxx, 11, 12, 13, 0, 0, -xxxxx.
Can you tell me why?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
  # include <iostream>
using namespace std;

int main()
{
	int array[5] = {11,12,13};
	int * a = array+2;
	cout << * a << endl;
	for(int j = -3; j < 4 ; j++)
		cout << *(a+j) << ", ";
	system("pause");
	return 0;
}
Last edited on
You can use any number for the index of the array - it is not prohibited.
Hi,

a is 2, j is -3, so a +j is -1.

It's all academic, it's not sensible to access out bounds.
But the compiler show the answer is :
array[-3],array[-2],array[-1],array[0],array[1],array[2],array[3].
-xxxxx, 11, 12, 13, 0, 0, -xxxxx.

Not exactly.

The program will display the contents of:
array[-1],array[0],array[1],array[2],array[3], array[4],array[5]

You need to take into account that pointer a holds the address of array[2], not array[0].
Topic archived. No new replies allowed.