gpt4 book ai didi

c++ - 调用可变大小的数组作为参数

转载 作者:行者123 更新时间:2023-11-30 03:57:48 26 4
gpt4 key购买 nike

我试图制作一个程序,让用户决定二维数组的维度。编译时函数定义出错。为什么这是错误的,正确的做法是什么?

我正在使用 Dev-C++ 5.7.1 编译器(如果相关的话)。

#include<iostream>

using namespace std;

int R=0,C=0;

void func(int);

int main() {
cin>>R>>C;
int array[C][R];
// DO STUFF HERE
func(array);
// DO SOME MORE STUFF
return 0;
}

void func(int arr[][R]) {
// DO STUFF HERE
}

最佳答案

ISO-C++ 禁止 VLA。要动态分配数组,您需要使用一些原始指针技巧或使用 vector vector 。

vector 方法的 vector :

std::cin >> R >> C;
std::vector<std::vector<int>> array(R, std::vector<int>(C));

func 的签名变为(const 正确性可能不同)

void func(const std::vector<std::vector<int>>& v);

以上是更容易、更易于维护、更安全、更短的解决方案。


用指针和指向指针的指针你可以做到,但它变得更复杂,你需要delete所有你new

int R, C;
std::cin >> R >> C;
int **array = new int*[R]; // allocates space for R row pointers
for (int i = 0; i < R; ++i) {
array[i] = new int[C]; // for each row, allocate C columns
}

func(R, C, array);

//then delete everything
for (int i = 0; i < R; ++i) {
delete [] array[i]; // delete all of the ints themselves
}
delete [] array; // delete the row pointers.

func 的签名是

void func(int r, int c, int **arr);

同样,vector of vectors 对您来说会容易得多。

关于c++ - 调用可变大小的数组作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27784014/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com