gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:40:36 25 4
gpt4 key购买 nike

我正在尝试使用 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。

关于c++ - 为什么二维动态数组有初始值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31550244/

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