-1

I created an array of

int A[5] = {2,4,6,8,10};

and made two pointers

int *p=A, *q=&A[5];

since there's only five elements in the array, as far as I understand in c++, when there's nothing it's supposed to be zero.

When I try to print out

cout<<"*p = "<<*p<<endl;
cout<<"*q = "<<*q<<endl;

I got this one instead

*p = 2
*q = 32766

I might be wrong about pointer p, it's pointing to the the first element by default.

But I don't understand why such a huge value is printed in pointer q, even though it's not even memory address in heap.

Can someone explain to me what's happening?

cigien
  • 57,834
  • 11
  • 73
  • 112
  • Does this answer your question? [Dereferencing one past the end pointer to array type](https://stackoverflow.com/questions/52727045/dereferencing-one-past-the-end-pointer-to-array-type) – Joe Sep 05 '20 at 11:37

2 Answers2

3

As far as I understand in c++, when there's nothing it's supposed to be zero.

You've misunderstood.

cout<<"*q = "<<*q<<endl;

Here you indirect through a pointer that points outside the bounds of the array, and attempt to access a non-existing element. The behaviour of the program is undefined.

Can someone explain to me?

Behaviour of the program is undefined. The behaviour could be anything. This time you observed the output of 32766. That is one possible behaviour among all behaviours that a program can have.

Undefined behaviour is to be avoided.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • As for why it prints out some arbitrary number, the UB manifests as simply printing out whatever memory is at that location as if it was an integer. – Justin Jun 26 '20 at 16:38
  • 3
    @Justin To be more accurate: UB appeared to have manifest*ed* like that. There are no guarantees that it would manifest like that always. – eerorika Jun 26 '20 at 16:40
2

A[5] contains only 5 elements, so the only indexes that are valid are 0 to 4.

So while you can refer to the address of A[5]:

int *q = A + 5;  // fine

this address is not pointing to valid memory, and dereferencing this address invokes undefined behavior.

cout << *q; // ub

Also note that:

int *q = &A[5];  // ub

is also UB, because the right hand side becomes &(A[5]), but A[5] invokes UB straight away.

UB means anything can happen. In your case, some value got printed to the screen, but there's no guarantee of that happening.

cigien
  • 57,834
  • 11
  • 73
  • 112