在C中使用char数组作为二维数组

时间:2012-09-25 10:51:36

标签: c pointers casting multidimensional-array

我有一个包含unsigned char *的结构,用于存储任意数据。在某些时候,我想使用这些数据,就好像它是一个二维数组。我就是这样做的:

#define DATA_SIZE 10
unsigned char *data = malloc(DATA_SIZE * DATA_SIZE * sizeof(unsigned char));

// this is not allowed
unsigned char (* matrix)[DATA_SIZE] = (unsigned char*[DATA_SIZE]) &data;

// this gives a warning and doesn't work at all
unsigned char (* matrix)[DATA_SIZE] = (unsigned char **) &data;

我想将指向任意数据的指针转换为二维数组,但当然我无法转换为数组类型。我怎么需要这个呢?

提前致谢。

1 个答案:

答案 0 :(得分:4)

你得到了强制转换的语法,

unsigned char (* matrix)[DATA_SIZE] = (unsigned char(*)[DATA_SIZE]) data;
通过删除#define

修复=后,

正常工作

#define DATA_SIZE 10

    unsigned char *data = malloc(DATA_SIZE * DATA_SIZE * sizeof(unsigned char));

    // this is the correct way to cast
    unsigned char (* matrix)[DATA_SIZE] = (unsigned char(*)[DATA_SIZE]) data;