【发布时间】:2018-11-07 11:15:55
【问题描述】:
当我们在堆栈上创建一个数组时,大多数编译器都想知道数组的大小,这将在编译时确定,所以通常我们不能让用户从标准输入中输入数组的大小,但是如果我们调用一个函数并将用户输入的数字传递给一个函数来创建一个数组怎么办?
这个函数不是在编译时调用的吗?
例如,如果用户输入 1,这个函数不是在运行时被调用吗? 由于用户将决定是否调用该函数。
或者这仍然是编译时间?
#include <iostream>
void someFunction(int number){
int sampleArray[number];
for(int i = 0; i < number; i++){
sampleArray[i] = 0;
}
// I know what I'm doing is pointless but is it possible?
}
int main()
{
int number = 0;
int choice = 0;
std::cout << "do you want to create an array? press 1 for yes" << std::endl;
std::cin >> choice;
if(choice == 1){
std::cout << "enter size" << std::endl;
std::cin >> number;
someFunction(number);
}
}
【问题讨论】:
-
编译时不调用任何东西。
-
使用
return sampleArray;,返回局部变量的地址,以及悬空指针。 -
非常好的观点
标签: c++ c++11 variable-length-array