有没有办法在运行时创建C++中的静态数组。 我想要的非常简单,只是想从用户获取输入数字并在运行时创建大小为输入数字的静态数组。不需要使用new操作符,也不需要指针,只需要静态数组。
main
之前),不会分配任何static
变量。您需要的是动态(在运行时创建的)数组。如果您想避免使用new
,则可以在堆栈上创建它(通过将参数传递给将创建它并在该函数内部处理它的函数),但这与static
不同。您还可以使用模板容器来为您分配和调整大小(例如其他答案中提到的std::vector
)。
编辑
似乎有些人对我没有提及初始化static
对象的问题感到困扰。虽然与问题无关,但值得知道静态成员变量或作用域内的静态变量可以在运行时初始化,但它们的空间在main
之前保留,因此变量的大小不能更改。static
变量在程序代码实际运行之前就被创建了”。 “created”表示构造函数运行。你可能正在寻找“allocated”或“storage is reserved”。 - Ben Voigtunsigned size;
std::cin >> size;
int arr[size];
答案是: 不行。C99有一个叫做变长数组的特性,但是C++03(和'0x)标准没有这种特性。
std::cin
;) - Marlonalloca
来在堆栈上分配内存,这相当于C99的可变长度数组。 - Aaron McDaid使用alloca函数在堆栈上分配空间,类似于静态数组或C99变长数组。
#include <iostream>
#include <alloca.h>
int main() {
unsigned sz;
std :: cin >> sz;
int * p = static_cast<int*>(alloca(sz * sizeof(int)));
// do stuff with p, do not attempt to free() it
}
我只在C中使用过它,但是它的效果很好。不过建议先阅读相关资料,它可能不太可移植。
不需要。
根据定义,您需要在运行时动态分配任何大小未知的内容。这就是为什么有new
和相关函数存在的原因。
数组是静态的
,这对您意味着什么?您认为它有哪些优势?
实际上,任何静态
变量(包括数组)都在程序开头预留了其存储空间。因此,在程序开始运行之前必须知道其大小,因此它不能以任何方式依赖用户输入。
然而,有许多方法可以创建动态的非静态数组,请告诉我们您想要做什么。
听起来你想要的是一个数组,它的大小在运行时定义,但其生命周期由静态存储期(即程序的长度)定义。
你不能使用语言中内置的基本数组。这些对象的大小在编译时定义,无法在运行时修改。但有几个替代方案。
基本的std::vector可能是你想要的:
std::vector<int> data;
int main()
{
int size;
std::cout << "Input the size of the array\n";
std::cin >> size;
// This line sets the size of the container
// vector is basically a C++ wrapper around a dynamically sized array
data.resize(size);
// Now we can safely read values into the array (like) container.
for(int loop =0;loop < size;++loop)
{
std::cout << "Input Value " << loop << "\n";
std::cin >> data[loop];
}
}
static
,对你来说意味着什么? - Ben Voigt