声明一个动态大小的数组。

3

如果我想在主函数中声明一个动态大小数组,可以这样做:

 int m;
 cin>>m;
 int *arr= new int[m];

以下操作无法执行,因为编译器在编译过程中必须知道每个符号的大小,除非它是外部符号:

 int m;
 cin>>m;
 int arr[m];

我的问题是:

  1. Why does the compiler have to know the size of arr in the above code? It is a local symbol which is not defined in the symbol table. At runtime, the stack takes care of it(same way as m). Is it because the compiler has to ascertain the size of main() (a global symbol) which is equal to the size of all objects defined in it?

  2. If I have a function:

    int func(int m)
    

    Could I define int arr[m] inside the function or still I would have to do

    int *a= new int[m]
    

2
有些编译器可以将第二个作为扩展进行编译。可变长度数组实际上是在C99中引入的。 - chris
2个回答

2
例如:
int MyArray[5]; // correct

或者

const int ARRAY_SIZE = 6;
int MyArray[ARRAY_SIZE]; // correct

但是
int ArraySize = 5;
int MyArray[ArraySize]; // incorrect

这里也解释了Bjarne Stroustrup的《C++程序设计语言》中所述的内容:
数组的元素数量,即数组的边界,必须是一个常量表达式(§C.5)。如果需要变量边界,请使用向量(§3.7.1,§16.3)。例如:

你的链接除了主页之外什么也没有。 - Rapptz
@Rapptz 你期望什么?一个非法复制品的链接吗? - obataku
在所有这些链接讨论中,我发现值得指出的是该网站现在位于http://www.stroustrup.com。 - chris
@Rapptz,请不要玩弄代码。请探索。 - shail
@oldrinb 不是吗?他链接到一个之前(可能)可用的目录的网站,现在不行了。 - Rapptz

1

回答您的问题:

1)问:为什么编译器需要在上面的代码中知道 arr 的大小?

答:如果您生成汇编输出,您会注意到一个固定值的“减法”来在堆栈上分配数组。

2)问:我能在函数内定义 int arr[m] i ... 吗?

答:当然可以。但是在您退出函数时它将成为无效;)

基本上,您不想要一个“数组”。C++“向量”将是一个很好的替代品:

std::vector<A> v(5, A(2));

这里有一些您可能会喜欢的链接:


@paulsm4...关于您的第二个答案...如果数组边界必须是常量表达式的规则,那么如果'm'的值直到运行时才确定,编译器如何允许将其作为数组边界。 - AvinashK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接