简体   繁体   English

在C ++中使用1D数组初始化2D数组

[英]Initialising 2d array using 1 d array in c++

Use of 2d array initialisation is forbidden and I am getting this error - 禁止使用2d数组初始化,并且出现此错误-

I am instructed to use main() as it is and i can only edit other two functions . 我被指示按原样使用main(),并且我只能编辑其他两个函数。

source.cpp(81): error C4700: uninitialized local variable 'Array' used
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Code: 码:

int main(){
    int **Array;
    Array = getArray2D(10, 10, Array);
    for (int i = 0; i<10; i++)
    for (int j = 0; j<10; j++){
        Array[i][j] = 4;
    }
    cout << endl;

    for (int i = 0; i<10; i++){
        for (int j = 0; j<10; j++){
            cout << Array[i][j];
        }
        cout << endl;
    }
    getchar();

    return 0;
}



int* getArray1D(int n, int *A)
{
    A = new int[n];
    for (int i = 0; i < n; ++i)
        A[i] = 0;
    return A;
}
int** getArray2D(int m, int n, int** A)
{
    // m array of integers
    A = new int*[m];
    for (int i = 0; i < m; ++i)
    {
        // create a 1d array on each element of a A
        A[i] = getArray1D(n, A[i]);

    }
    return A;
}

How can i correct this ? 我该如何纠正?

The problem is that you don't initialize the Array to NULL and then you use it. 问题是您不将Array初始化为NULL,然后使用它。

So change this: 所以改变这个:

int **Array;
Array = getArray2D(10, 10, Array);

to this: 对此:

int **Array = NULL;
Array = getArray2D(10, 10, Array);

What you get is actually a warning, not an error, that looks like this: 您得到的实际上是警告,而不是错误,看起来像这样:

warning: ‘Array’ is used uninitialized in this function [-Wuninitialized]

Don't forget to de allocate your memory later! 不要忘了以后取消分配内存!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM