首页 文章

多维数组和指向那些具有一个Typedef的数组的指针

提问于
浏览 333
0

此代码有效,允许我通过指针数组访问2D数组:

typedef uint8_t IMAGE_TYPE[4][8];
typedef uint8_t (*IMAGE_PTR_TYPE)[8];
IMAGE_TYPE test1 = {{0,1,2,3,4,5,6,7},
                    {0,1,2,3,4,5,6,7},
                    {0,1,2,3,4,5,6,7},
                    {0,1,2,3,4,5,6,7}};
IMAGE_TYPE test2 = {{10,11,12,13,14,15,16,17},
                    {10,11,12,13,14,15,16,17},
                    {10,11,12,13,14,15,16,17},
                    {10,11,12,13,14,15,16,17}};
IMAGE_PTR_TYPE test_ptr_array[] = {test1, test2};

但是,我真的很惹恼我有两个typedef . 看来我应该只需要一个,并且这段代码应该有效:

IMAGE_TYPE *test_ptr_array[] = {test1, test2};

但是,它没有给我这个错误:

错误:无法在初始化时将'uint8_t()[8] {aka unsigned char()[8]}'转换为'uint8_t()[4] [8] {aka unsigned char()[4] [8]}'

C有没有办法只用一个typedef来处理这个问题?

1 回答

  • 2

    这是一种方式:

    typedef uint8_t ROW_TYPE[8];
    
    ROW_TYPE test1[] = {{0,1,2,3,4,5,6,7},
                    {0,1,2,3,4,5,6,7},
                    {0,1,2,3,4,5,6,7},
                    {0,1,2,3,4,5,6,7}};
    ROW_TYPE test2[] = {{10,11,12,13,14,15,16,17},
                    {10,11,12,13,14,15,16,17},
                    {10,11,12,13,14,15,16,17},
                    {10,11,12,13,14,15,16,17}};
    
    ROW_TYPE *test_ptr_array[] = {test1, test2};
    

    使用此方法,您可以访问 test_ptr_array[0][1][2] 等数字,它们会给出 test1[1][2] .

相关问题