问题描述
我想创建一个可变长度的全局数组,以便可以在诸如main()之类的任何函数中使用它们。
#include <iostream>
int g_t_step[];
int main()
{
g_t_step[1]=1;
std::cout << g_t_step[1];
}
解决方法
通常,除了记录之外,全局变量不是唯一的选择。轻松地了解哪些函数/方法将修改数组的内容,并且随着代码库的增长,它可能变得难以调试。如果您提供有关您要实现的目标的更多详细信息,将为您提供帮助。
通过查看您的代码示例,我猜您对C ++还是很陌生,您编写的代码无法编译。您在此处定义的变量g_t_step
也应初始化,例如:
int g_t_step[] = {1,2,3};
但是,如果要调整数组的大小,则无法以这种方式声明它,因为无论您尝试做什么,g_t_step
的大小都是3(在我的示例中,因为左边有3个数字侧)。这样做的原因是因为g_t_step
已分配在编译时定义的堆栈上。
如果您希望它可调整大小,则应像这样将其分配在堆上:
#include <iostream>
int* g_t_step = nullptr;
int size = 0;
int capacity = 0;
int main() {
g_t_step = new int[10]; // heap allocation
capacity = 10;
g_t_step[0] = 4 // initialize the second element of the array
size = 1;
std::cout << g_t_step[0] << '\n';
return 0;
}
这将是回答您问题的方法,但是它很小,您必须自己跟踪数组的当前大小和其中的元素数量。简单的方法是像这样使用STL的std :: vector模板:
#include <iostream>
#include <vector>
// the static part is not necessary if you only have one file
// but is usefull if you define g_t_step in another source file
// which is then linked against the main
static std::vector<int> g_t_step;
int main() {
g_t_step.push_back(1); // initialize the first value...
g_t_step.push_back(2); // second...
g_t_step.push_back(3); // and third...
std::cout
<< g_t_step.size() << ' ' // output 3 because the vector contains 3 numbers
<< g_t_step.capacity() << ' ' // output 4
<< g_t_step[0] << ' ' // output 1
<< g_t_step[1] << ' ' // output 2
<< g_t_step[2] << '\n'; // output 3
}
类std :: vector跟踪元素数(size())和数组的大小(capacity()),该值始终是元素数(在这种情况下为4)的2的幂)。
然后您可以编写如下内容:
static std::vector<int> vect;
void add_element(int e) {
vect.push_back(e);
}
int main() {
add_element(4);
add_element(5);
std::cout << vect[0] << ' ' << vect[1] << '\n'; // output: 4 5
}
但是再次,这被认为是不好的做法,因此如果没有更多细节,除非是用于小脚本,否则我不建议您使用它。
有关更多信息,请参见: std::vector
您还可以查看静态变量。
,可变长度数组的概念适用于C99,但不适用于C ++标准。以一种增强的方式,您可以利用C ++中的向量帮助。它们具有调整大小和重新分配所需内存以正确使用它们的能力。
假设以下示例代码并注意注释:
#include <iostream>
#include <vector>
int main(void) {
// Example 1: Manually resizing the vector
// ---------------------------------------
std::vector<int> myVec;
int n = 100;
myVec.resize(n); // Similar work to that of VLAs
// Example 2: Dynamically managing the size of vector
// --------------------------------------------------
std::vector<int> myVec {10,20,30};
std::vector<int> myVec2;
myVec.push_back(10);
myVec.push_back(20);
// After this,the size of the vector will be increased by 2
// since two elements are inserted.
// You can erase() the vector elements and the sizes will be
// automatically reduced.
.
.
return 0;
}
另一方面,您不应该考虑全局声明变量。
,您没有初始化数组大小。 这会在编译时给您错误
与写作时一样
int a
然后,将变量“ a”存储在具有随机地址且大小为int(取决于处理器)的堆栈存储器中
但是当你写
int a[]
然后,堆栈内存需要数组的大小才能在堆栈内部分配
例如int a[3]
;
这将在堆栈内存中获取3 *(int的大小)
正如我上面讨论的,数组的静态分配直接存储在堆栈中 但您也可以在堆内部分配数组,这称为动态分配。我认为您首先必须自己尝试动态分配