Pointer to a type inside a macro, C

I had a problem trying to express a type pointer inside a macro.

Take this simple example.

#define INDEX_OF_DATA(data, type, index) \ ((type *)data)[index] 

It works:

 INDEX_OF_DATA(buffer, float, 3); 

If this fails:

 INDEX_OF_DATA(buffer, float[2], 3); 

Since the cast should be (float(*)[2]) .

Is there a way to express a "pointer to type " ... without using typeof ? (which is not standard C).


Please note: there are, of course, other ways for this particular example to work. e.g. for char and offset by sizeof(type) * index . But I'm interested in a way to express pointer to type in C.

+7
c c-preprocessor
source share
2 answers

Doing hard things with C types can be a fun sport, but it is very confusing in real code.

To avoid over-breaking heads over complex pointer expressions, people often use typedef !

If you typedef all the types that you expect to use with this macro, you will not have any problems. Note:

 #include <stdlib.h> #define INDEX_OF_DATA(data, type, index) \ ((type *)data)[index] int main(void) { float (*buffer)[2] = malloc(4 * sizeof(float[2])); typedef float t_f2arr[2]; INDEX_OF_DATA(buffer, t_f2arr, 3)[0] = 1.1f; return 0; } 

This is what you intended!

+1
source share

If we want to keep the original macro, we can use this trick:

 #define INDEX_OF_DATA(data, type, index) ((type*)data)[index] struct mystruct { float f[2]; }; mystruct* p = &INDEX_OF_DATA(buffer, mystruct, 3); 

Unfortunately, a structure overlay can affect this decision, so it’s better to check:

 static_assert(sizeof(mystruct) == sizeof(float (*)[2]), "padding found"); 
0
source share

All Articles