Home > Software design >  Cast to the pointer to array of structs
Cast to the pointer to array of structs

Time:09-29

I have a pointer to the array of structs:

struct myStruct (*str_ptr)[];

I try to assign to it a value i have in another pointer which type is (uint8_t*) When I do:

uint8_t* ptr2;
ptr2 = (some memory adress);
str_ptr = ptr2;

I get a warning: "assignment to 'myStruct (*)[]' {aka 'struct <anonymous> (*)[]'} from incompatible pointer type 'uint8_t *' {aka 'unsigned char *'} [-Wincompatible-pointer-types]"

Obvious solution to the problem is to cast ptr2 to the type of str_ptr... and I tried many configurations, but all casts I can think of returns in compiler error. Anyone know how to cast a pointer to the "pointer to the array of structs"?

Edit: Sorry, I will try to describe what I'm trying to do here. I have some data on external memory, and firstly I declare memory for it:

ptr2 = malloc(data_size);

Then fill it with some data using memcpy (thats why I want it to be (uint8_t*) type). Lastly, I try to assign my pointer to the array of structs to the place where the data starts, so i can access it by typing (*str_ptr)[3].field for example.

CodePudding user response:

Pointers to arrays can present tricky C syntax issues. However, a very strong hint for the type of cast required to avoid a compiler warning is given in the message you have quoted: "assignment to 'myStruct (*)[]'

However, that type isn't quite complete, because you also need the struct keyword.

So, your warning-free cast assignment would be like this:

str_ptr = (struct myStruct(*)[])ptr2;
  • Related