c++为变量分配数组大小并在运行时为变量赋值?

时间:2022-01-21 03:12:45

I am really new to C++ programming so please pardon my silly question.

我对c++编程很陌生,请原谅我的愚蠢问题。

I have an array that looks like this:

我有一个这样的数组:

double myarray [15][20000]; // Works ok but stack overflow error if I change 15 to about 200

I would like to achieve something like this:

我想实现这样的目标:

double myarray [total][20000];

then at runtime I want user to input the value of total:

然后在运行时,我希望用户输入total的值:

cin>>total

Please advice on how to acheive this and what is the best practice to solve this and avoid stack overflow.

请建议如何解决这个问题,以及解决这个问题和避免堆栈溢出的最佳实践是什么。

Thanks.

谢谢。

1 个解决方案

#1


4  

Use a vector of vectors:

使用向量的向量:

int total;

cin >> total;

//                                      (1)                        (2)
std::vector<std::vector<double>> myVec(total, std::vector<double>(20000));
// (1) is the first dimension and (2) is the second dimension

And you can use them just like an array, and you won't get a stack overflow:

你可以像数组一样使用它们,你不会得到堆栈溢出:

myVec[0][4] = 53.24;
cout << myVec[0][4];

And you can even make them bigger on the fly if you need to.

如果你需要的话,你甚至可以把它们放大。

You're getting a stack overflow because the stack is usually pretty small and you are trying to allocate too big an array on it. vector uses dynamically allocated memory on the free store which is usually much bigger and won't give you an overflow error.

您会得到堆栈溢出,因为堆栈通常非常小,并且您试图在其上分配太大的数组。vector在免费存储上使用动态分配的内存,通常要大得多,不会产生溢出错误。

Also, in C++ the size of static arrays must be known at compile time which is why you can't read in a number and use that, whereas with vectors you can resize them at runtime.

此外,在c++中,静态数组的大小必须在编译时就知道,这就是为什么您不能读取一个数字并使用它,而对于向量,您可以在运行时调整它们的大小。

#1


4  

Use a vector of vectors:

使用向量的向量:

int total;

cin >> total;

//                                      (1)                        (2)
std::vector<std::vector<double>> myVec(total, std::vector<double>(20000));
// (1) is the first dimension and (2) is the second dimension

And you can use them just like an array, and you won't get a stack overflow:

你可以像数组一样使用它们,你不会得到堆栈溢出:

myVec[0][4] = 53.24;
cout << myVec[0][4];

And you can even make them bigger on the fly if you need to.

如果你需要的话,你甚至可以把它们放大。

You're getting a stack overflow because the stack is usually pretty small and you are trying to allocate too big an array on it. vector uses dynamically allocated memory on the free store which is usually much bigger and won't give you an overflow error.

您会得到堆栈溢出,因为堆栈通常非常小,并且您试图在其上分配太大的数组。vector在免费存储上使用动态分配的内存,通常要大得多,不会产生溢出错误。

Also, in C++ the size of static arrays must be known at compile time which is why you can't read in a number and use that, whereas with vectors you can resize them at runtime.

此外,在c++中,静态数组的大小必须在编译时就知道,这就是为什么您不能读取一个数字并使用它,而对于向量,您可以在运行时调整它们的大小。