是否有可能在c++中声明main函数中的全局变量?如果可能的话,怎么做
Is it possible to declare a global variable inside main function in c++? If possible how?
要解决问题,我需要一个2D数组,应该由其他函数访问。我觉得传递指针然后在其他函数中使用指针是有问题的。因为数组的尺寸依赖于输入,所以我不想声明一个巨大的2D全局数组。
我想在main中声明一个2D数组作为全局数组并从其他函数中访问它。
在c++中,如果你需要一个可变大小的数组,99%的情况下,你应该使用std::vector
.
std::vector
,并在main
中指定所需的大小。
从你的问题标题
是否可以在c++中声明main函数中的全局变量?如果可能,怎么做?
不,这是不可能的声明全局变量在main()
内,或任何其他函数的作用域。全局变量必须在任何函数作用域之外声明。
正如你所提到的,数组的大小取决于运行时的输入,数组的大小不能在编译时确定。
即使你的编译器支持VLA,这些也不能在全局范围内使用。
正如@Brian已经指出的那样,您需要在运行时提供一些动态内存分配,例如std::vector
:
std::vector<int> myArray;
void initArray() {
int arraySize;
std::cout << "Enter array size: ";
std::cout.flush();
if(std::cin >> arraySize) {
myArray.resize(arraySize);
}
}
可以使用指向std::vector的指针。下面是一个示例代码,
#include <iostream>
#include <vector>
using namespace std;
vector<int>* v;
int main(){
int n;
cin >> n;
v = new vector<int>(n);
// now you can simply pass the vector to any function
}
相关文章:
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 当vector是tje全局变量时,c++中vector的内存管理
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 内联函数中具有内部链接的全局变量
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 全局变量 多读取器 一个写入器多线程安全?
- 如果全局变量默认是外部变量,为什么要添加"extern"关键字?
- 不同作用域中的静态变量和全局变量
- C++ 在编译时具有函数计算全局变量
- 将引用分配给局部变量,如果局部变量超出范围,它会超出范围吗?
- 修改程序的入口点时未调用全局变量的构造函数
- 使用 std::ios_base::Init 正确初始化全局变量
- 为什么我的全局变量似乎没有变化?
- C ++程序如何返回我的数组或写入全局变量
- 为什么我的数组值与此处的全局变量不匹配?
- 如果全局变量的声明引发异常,如何退出C++程序
- 如果全局中存在相同的变量,如何访问匿名命名空间变量
- 如果用调试信息编译,则通过其名称获取全局变量地址
- 是否有可能在c++中声明main函数中的全局变量?如果可能的话,怎么做
- 如果需要从配置文件初始化全局变量,如何在项目中共享全局变量