2

If I declare two arrays, one on the stack and one on the heap, I get different behavior when printing the variable name (in gdb if that matters).

int array_on_stack[5];

int * array_on_heap = new int[5];

Now in gdb I step through each line of code and then print the variable name, expecting to get the memory address for each.

print array_on_stack

print array_on_heap

But for array_on_stack it prints the contents of the array and not the memory address. In order to get the memory address I need the command print &array_on_stack. This suggests that array_on_stack is not a pointer. Can some explain the difference between these two declarations in terms of how to access their memory address and why this is the case?

trincot
  • 317,000
  • 35
  • 244
  • 286
xjtc55
  • 389
  • 2
  • 4
  • 14
  • That's because they're not the same, one's a pointer, and ones an array; they're different things. – UKMonkey Oct 19 '16 at 13:21
  • 2
    *This suggests that array_on_stack is not a pointer* You are correct. Arrays are not pointers. pointers are pointers and arrays are arrays. just like `int`s are not `double`s. – NathanOliver Oct 19 '16 at 13:22

1 Answers1

5

Your array_on_heap is not an array: it's a pointer (to the first item of a dynamically allocated array).

Arrays are arrays, pointers are pointers.

Hence you will get similar results in gdb for

int* array_with_automatic_storage = &array_on_stack[0];
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • I thought in C++ arrays degrade to pointers so that the variable name was simply a pointer pointing to the first object. That is why we can declare arrays in both ways. – xjtc55 Oct 19 '16 at 13:23
  • @xjtc55: Yes, in the declaration above you can replace `&array_on_stack[0]` with just `array_on_stack`, taking advantage of implicit conversion to pointer, an array expression /decay/ to pointer type. But array expressions don't always decay and arrays are not pointers. In particular you can't assign a pointer to an array variable. – Cheers and hth. - Alf Oct 19 '16 at 13:28
  • 2
    There is a [C++ array FAQ](http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c) question here on SO, mostly written by Fred Overflow and me. You could do worse than reading it. There is also some [C++ array documentation](http://stackoverflow.com/documentation/c%2b%2b/3017/arrays#t=201610191331403254374) here on SO, created and mostly written by me. I mention the authors up front as common disclosure. – Cheers and hth. - Alf Oct 19 '16 at 13:33