1

我有一个包含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;

我想将指向任意数据的指针转换为二维数组,但当然我不能转换为数组类型。我需要怎么做?

提前致谢。

4

1 回答 1

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;
于 2012-09-25T11:06:19.053 回答