C ++如何从函数返回动态分配的2D数组

时间:2017-11-30 12:57:26

标签: c++ arrays

每次运行时都会出现内存错误。我甚至关闭了吗?

int **createField(int N, int ** ary) {
    ary = new int*[N];
    for(int i = 0; i < N; ++i)
        ary[i] = new int[N];

    for(int i = 0; i < N; ++i)
        for(int j = 0; j < N+1; ++j)
            ary[i][j] = 0;

    return ary;
}

int playGame (int N, int ** ary) {
    cout<<"Enter the coordinates of the " << N << " shots:"<<endl;
    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < N; j++)
        {
            cout<<"Enter element ["<<i<<"]["<<j<<"]: ";
            cin>>ary[i][j];
        }
    }
    return 0;
}

int main() {
    int N;
    cout << "Enter the number of Redshirts: ";
    cin >> N;
    int** ary;
    createField(N, ary);
    playGame(N, ary);
 }

1 个答案:

答案 0 :(得分:2)

以下内容未初始化ary

int** ary;
createField(N, ary);

应该是

int** ary;
ary = createField(N, ary);

但实际上createField的第二个参数是不需要的,所以它将是

int **createField(int N) {
    int** ary = new int*[N];
    for(int i = 0; i < N; ++i)
        ary[i] = new int[N];

    for(int i = 0; i < N; ++i)
        for(int j = 0; j < N+1; ++j)
            ary[i][j] = 0;

    return ary;
}

然后

int** ary = createField(N);

但更好的方法是使用std::vector手动处理内存。