C++中结构体的 二维数组 初始化方法和顺序是怎样的?
高洛峰
高洛峰 2017-04-17 14:26:48
0
2
677

如现有一个结构体
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行。。。我觉得不理解。。。也不确定源码有没有错误。有没有人能帮忙解答?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
PHPzhong

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.

刘奇

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!