This question already has an answer here:
这个问题已经有了答案:
- Is an array name a pointer? 10 answers
- 数组名是指针吗?10个答案
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).
如果我声明两个数组,一个在堆栈上,另一个在堆上,那么在打印变量名时(如果重要的话,在gdb中),我将得到不同的行为。
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.
现在,在gdb中,我遍历每一行代码,然后打印变量名,希望得到每个代码的内存地址。
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?
但是对于array_on_stack它输出数组的内容而不是内存地址。为了获得内存地址,我需要命令print &array_on_stack。这表明array_on_stack不是一个指针。有人能解释一下这两个声明在如何访问它们的内存地址以及为什么会这样吗?
1 个解决方案
#1
5
Your array_on_heap
is not an array: it's a pointer (to the first item of a dynamically allocated array).
array_on_heap不是一个数组:它是一个指针(指向一个动态分配数组的第一个条目)。
Arrays are arrays, pointers are pointers.
数组是数组,指针是指针。
Hence you will get similar results in gdb for
因此,您将在gdb for中得到类似的结果
int* array_with_automatic_storage = &array_on_stack[0];
#1
5
Your array_on_heap
is not an array: it's a pointer (to the first item of a dynamically allocated array).
array_on_heap不是一个数组:它是一个指针(指向一个动态分配数组的第一个条目)。
Arrays are arrays, pointers are pointers.
数组是数组,指针是指针。
Hence you will get similar results in gdb for
因此,您将在gdb for中得到类似的结果
int* array_with_automatic_storage = &array_on_stack[0];