我通过一个名为 size 的变量动态传递数组大小,它在 c 中工作正常,但在 c++ 中不行。请告诉我原因,先谢谢了。
#include <iostream>
#include <stdlib.h>
using namespace std;
int size;
int main(int argc, char *argv[])
{
int i ;
int *a[size];
cout<<"Enter size";
cin >> size;
for(i =0; i < size ;i++)
{
cout<<"Enter value:" ;
cin>>a[i] ;
}
for(i=0 ; i < size; i++)
{
cout<<a[i]<< " ";
}
system("PAUSE");
return 0;
}
我已经通过适当的 I/O 更改执行了相同的程序,它执行正确。
还请帮助我了解编译器在这种情况下在数组声明时的行为方式。
最佳答案
Please tell me the reason
原因是C++没有变长数组。也许您正在寻找std::vector<int>
(可能)或new int
(不太可能)。
Also please help me in understanding how compiler is behaving in this case at the time of array declaration.
就像它在任何其他情况下的行为一样:它解析源文本并输出语义与源代码的语义相对应的机器代码。只是变长数组的大小不是硬编码为常量,而是存储在寄存器或堆栈上(就像某种“变量”),以及大小计算(指针算术,特别是)再次执行该存储的值。
关于c++ - 在 C 和 C++ 中动态声明数组大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17896024/