如现有一个结构体
typedef struct
{
uint8_t a;
uint8_t b[10];
uint8_t c[3];
}basic;
而定义一个二维数组
basic array[][5],如何对其初始化?
是这样吗:
basic array[][4]=
{
{1,0,0},
{2,0,0},
{3,0,0,0,1},
{2,2,1,2,2},
{3,1,1,4,2,2,4},
}
如果按这样初始化,
array的array0,array0,...array2...
分别都是什么呢?
array一共有几行呢?
我看到一个源码里面的意思好像是,这样初始化过后,array有5行。。。我觉得不理解。。。也不确定源码有没有错误。有没有人能帮忙解答?
PHPz2017-04-17 14:28:48
Just think of that struct
as an ordinary int[14]
. It is the initialization of a two-dimensional array. You can print it out like this.
#include <iostream>
using namespace std;
typedef struct
{
uint8_t a;
uint8_t b[10];
uint8_t c[3];
}basic;
int main()
{
basic array[][4]=
{
{1,0,0},
{2,0,0},
{3,0,0,0,1},
{2,2,1,2,2},
{3,1,1,4,2,2,4},
};
for (int i = 0; i < 5; ++i)
{
cout << (unsigned int)array[i][0].a << endl;
}
basic test[][5] =
{
{{1,0,0},
{2,0,0},
{3,0,0,0,1},
{2,2,1,2,2},
{3,1,1,4,2,2,4}}
};
for (int i = 0; i < 5; ++i)
{
cout << (unsigned int)test[0][i].a << " ";
}
cout << endl;
return 0;
}
Because uint8_t is the typedef of unsigned char, it is converted to unsigned int for output. . . .
Here is a blog post that introduces the initialization of two-dimensional arrays http://blog.csdn.net/chenshij...
I think the reason why this initialization is difficult to understand is because we usually initialize two-dimensional arrays with When enclosed in curly braces, it usually indicates the initialization of a line. In this problem, the initialization of the structure can be done using curly braces, which leads to some confusion. However, the curly braces here still represent the correct meaning. Initialization of an entire line, rather than initialization of a single structure element. To initialize the structures in this two-dimensional array one after another, you need to add layers of expansion like you did.
怪我咯2017-04-17 14:28:48
You will understand if you imagine each row of the one-dimensional array you initialize as an element, and then imagine the entire two-dimensional array as a one-dimensional array that accommodates this element.
A two-dimensional array is actually an array of one-dimensional arrays. You can think of it as an array nested with several arrays of the same size. Each array element is an array, so when you declare it, the former number does not need to be there, depending on how many arrays you have initialized, but the latter number must be there because the size of each element must be determined.