1

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.

1 Answer 1

4

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, and the #define was incorrect of course, I changed it in my question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.