Cast a struct of ints to an array of ints

后端 未结 4 583
日久生厌
日久生厌 2021-01-20 01:52

I am using a library that has a function that takes an array of structs. That struct and function has the following layout:

struct TwoInt32s
{
  int32_t a;
         


        
4条回答
  •  Happy的楠姐
    2021-01-20 02:41

    You could allocate structures but treat their members as a sort of virtual array:

    struct TwoInt32s *buffer = malloc(len * sizeof *buffer);
    
    #define BUFFER(i) (*((i)%2 ? &buffer[(i)/2].b : &buffer[(i)/2].a))
    
    /* fill in the buffer, e.g. */
    for (int i = 0; i < len * 2; i++)
        BUFFER(i) = i;
    

    Unfortunately, neither GCC nor Clang currently "get" this code.

提交回复
热议问题