C中的多维数组初始化

use*_*911 11 c

我正在阅读Kochen的书"C语言编程",我很困惑他解释了多维数组的初始化

这里

特别是,我不理解下面句子的含义注意,在这种情况下,需要内部大括号来强制正确初始化.没有它们,第三行的前两行和前两个元素将被初始化.我不确定这句话意味着什么.

Jos*_*ers 14

这是因为M[4][5]数组有20个元素(4行,5列),如果没有使用内部大括号显式指定行,则初始化的默认顺序是逐行的.

这意味着如果您将相同的12个值分配为简单的线性列表,而没有内部的大括号,则将值分配给前两行(2*5 = 10个元素)加上第三个的前两个列行.(未明确初始化的数组的其余8个元素将自动设置为0.)

C编译器知道每行只有5列,并且每次达到5列边距时,会自动将数字列表包装到下一行.从而,

int M[4][5] = {10, 5, -3, 9, 0, 0, 32, 20, 1, 0, 0, 8};
Run Code Online (Sandbox Code Playgroud)

被理解为是指

int M[4][5] =
{
  {10,  5, -3, 9, 0},
  { 0, 32, 20, 1, 0},
  { 0,  8,  0, 0, 0},
  { 0,  0,  0, 0, 0}
};
Run Code Online (Sandbox Code Playgroud)

您可以通过使用内部大括号将12个值分隔为您自己喜欢的行来覆盖默认顺序(但对于此数组定义,每行自然不超过5列M).

例如,当您使用内部大括号将相同的12个值分隔为四个3个集合(如书中所示的页面)时,那些内部大括号将被解释为初始化多维数组的单独行.结果将初始化数组的四行,但只有这四行的前三列,将其余列设置为零(每行末尾两个空白零值).

也就是说,C编译器知道数组M每行有5列,因此它会将缺少的列添加到每一行,这样每行有5列,因此数组总共有20个值:

int M[4][5] =
{
  {10,  5, -3},
  { 9,  0,  0},
  {32, 20,  1},
  { 0,  0,  8}
};
Run Code Online (Sandbox Code Playgroud)

被理解为是指

int M[4][5] =
{
  {10,  5, -3, 0, 0},
  { 9,  0,  0, 0, 0},
  {32, 20,  1, 0, 0},
  { 0,  0,  8, 0, 0}
};
Run Code Online (Sandbox Code Playgroud)


Dan*_*l K 8

使用内括号,数组看起来像这样:

10  5 -3  0  0
 9  0  0  0  0
32 20  1  0  0
 0  0  8  0  0
Run Code Online (Sandbox Code Playgroud)

所以在每一行中最后2个值都为零(因为你没有为它们设置一个值.没有内括号,数组看起来像这样:

10  5 -3  9  0
 0 32 20  1  0
 0  8  0  0  0
 0  0  0  0  0
Run Code Online (Sandbox Code Playgroud)

只有前12个元素才会成为给定值,其余元素将为0.


Ale*_*sie 7

由于所有数组内部都表现为1d数组,因此您必须使用括号指定您初始化的行.

举个例子:

int a[4][5] = {
              { 1, 2, 3 },  // those are the elements of the first row.
                            // only the first 3 elements are initialized
              { 1, 2, 3, 4} // those are the elements of the 2nd row.
                            // only the first 4 element are initialized
              };
                            // everything else will be equal to 0
Run Code Online (Sandbox Code Playgroud)

int a[4][5] = { 1, 2, 3, 1, 2, 3, 4}; // this will initialize first 5 elements 
                                      // of the first row and then continue 
                                      // with the 2nd one making the first 2 
                                      // elements to be 3 and 4 respectivly
                                      // everything else will be equal to 0
Run Code Online (Sandbox Code Playgroud)