pancake
pancake

Reputation: 1943

Use char array as two dimensional array in C

I have a struct that contains an unsigned char * for storing arbitrary data. At some point I want to use this data as if it were a two-dimensional array. This is how I do it:

#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;

I want to cast a pointer to arbitrary data to a two-dimesional array, but of course I can't cast to array types. How would I need to go about this?

Thanks in advance.

Upvotes: 1

Views: 1618

Answers (1)

Daniel Fischer
Daniel Fischer

Reputation: 183908

You have gotten the syntax of the cast wrong,

unsigned char (* matrix)[DATA_SIZE] = (unsigned char(*)[DATA_SIZE]) data;

works after you fixed your #define by removing the =.

#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;

Upvotes: 4

Related Questions