是否可以使用以下代码来模拟动态分配的行为。例如,我们不知道存储在文件中的整数的确切数量,我们将读取该文件,然后将其存储在名为 Hello 的数组中。
int x;
int n=0;
ifstream input("a.dat");
while (!input.eof())
{
input >> x;
n++;
}
input.close();
int Hello[n];
cout << "n= " << n << endl;
int i=0;
while (!input.eof())
{
input >> Hello[i];
i++;
}
最佳答案
Is it possible to mimic the behavior of dynamic allocation using the following code.
不,主要区别在于程序中的数组存储在堆栈上,而所有动态内存分配都发生在堆上。
你到底在做什么,在你的代码中使用C++中C的C99标准的VLA功能。在 g++ 编译器中使用 -pedantic 选项进行编译将揭示这一点。由于 C++ 不直接支持它,并且它是特定于实现的语言扩展,因此如果您的目标是编写可移植代码,那么使用它并不是一个好主意。
VLA的使用alloca(
) ,在运行时在堆栈上分配内存,并讨论了这种技术的缺点here .
此外,VLA在运行时在堆栈上分配内存,如果值超出范围,程序就会崩溃,而使用VLA快速创建几个字节的数组是可以的,创建不确定数量的大内存可能不会为了安全起见,最好使用动态内存分配来处理。
关于c++ - 动态分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16259506/