为什么二维动态数组有初始值?

Why 2d dynamic array has initial values?

我正在尝试使用 new 运算符分配二维数组。这是我的函数 new2d.

int** new2d(int r, int c)
{
    int **t = new int*[r];
    for(int i = 0; i < r; i++)
        t[i] = new int[c];
    return t;
}

我很确定这是正确的方法。但是,当我尝试打印如下数组时

int **a = new2d(5, 9);
for(int i = 0; i < 5; i++)
{
    for(int j = 0; j < 9; j++)
    {
        cout << a[i][j] << " ";
    }
    cout << endl;
}

它以随机 13,10,7...

给出了这个奇怪的输出
0 0 0 0 13 0 0 0 0 
0 0 0 0 10 0 0 0 0 
0 0 0 0 7 0 0 0 0 
0 0 0 0 4 0 0 0 0 
0 0 0 0 0 0 0 0 0 

为什么会这样?

默认初始化可能导致不确定的值。引用自 http://en.cppreference.com/w/cpp/language/default_initialization

Default initialization is performed in three situations:

1) when a variable with automatic, static, or thread-local storage duration is declared with no initializer.

2) when an object with dynamic storage duration is created by a new-expression with no initializer or when an object is created by a new-expression with the initializer consisting of an empty pair of parentheses (until C++03).

3) when a base class or a non-static data member is not mentioned in a constructor initializer list and that constructor is called.

The effects of default initialization are:

If T is a non-POD (until C++11) class type, the constructors are considered and subjected to overload resolution against the empty argument list.

The constructor selected (which is one of the default constructors) is called to provide the initial value for the new object.

If T is an array type, every element of the array is default-initialized. Otherwise, nothing is done: the objects with automatic storage duration (and their subobjects) are initialized to indeterminate values.

你的情况符合条件2。

你似乎没有在 t[i] = new int[c]; 之后初始化数组 然而,这不是创建数组的最佳方式。这是一个更大的讨论 How do I declare a 2d array in C++ using new?

嗯。通常最好使用

这样的方法
int *array = new int[sizeX*sizeY];

ary[i][j] 然后被重写为 array[i*sizeY+j].

是的,最好阅读大讨论,更好地理解 + 和 -