3

朋友们,我只是在玩一些指针程序,并意识到 GCC(也许还有 C 标准)区分了静态和动态数组。

动态数组有一个用于数组中元素地址的占位符,而对于静态数组,没有编译器存储元素数组起始地址的内存位置。

我有一个示例程序来证明我的困惑。

#include <iostream>
#int main(void)
{
  int _static[10];
  int *_dynamic;

  _dynamic = new int [10];

  std::cout<<"_static="<<_static<<" &_static="<<&_static<<" &_static[0]="<<&_static[0]<<std::endl;
  std::cout<<"_dynamic="<<_dynamic<<" &_dynamic="<<&_dynamic<<" &_dynamic[0]="<<&_dynamic[0]<<std::endl;

  return 0;
}

对于上述程序,_static&_static[0]在预期的行上返回相同的地址。但是,它&_static也返回与其他两个相同的地址。

所以,_static&_static引用相同的数字(或地址我们想称呼它的任何东西)。正如预期的那样,_dynamic&_dynamic指示不同的位置。

那么,为什么 C 标准这么说_static并且&_static必须引用相同的位置。听起来很混乱。我觉得的一个原因是这&_static没有多大意义。但是,它的用法不应该被报告为错误吗?

有人可以帮我解决这个困惑吗?

4

3 回答 3

9

函数内部的静态数组在堆栈上分配。这样_static(衰减为指向第一个条目的指针),&_static[0]并且&_static具有相同的值,相同的内存地址。

On the other hand, a dynamic array is in fact a pointer to a contiguous memory area. Only the pointer is stored on the stack. This is why &_dynamic (from the stack) and _dynamic (from the heap) differ.

Hope this image shows it all:

static vs dynamic arrays

Have also a look at this article about static and dynamic global arrays continued with the distinction between extern and non-extern.

于 2012-07-12T04:42:04.903 回答
4

Actually _static and &_static don't refer to the same location. The only reason they appear to is because you use _static in a context in which it decayed into a pointer. That is, by the way you used them, you made them refer to the same location. But they didn't before you did that -- one was an array and the other was a pointer. They couldn't be the same because they were fundamentally different things.

于 2012-07-12T04:42:38.263 回答
0

in simple words static is created in stack and dynamic is created in heap, in static array you have to tell the size before program runs but in dynamic you can take input from user and then make array of that size.

Example static:

int array[5];

Example dynamic:

int *array;
cout << "Enter size of array: ";
cin >> size;
array = new int[size];
于 2012-07-12T08:14:14.980 回答