Cast a struct of ints to an array of ints

后端 未结 4 551
日久生厌
日久生厌 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条回答
  • 2021-01-20 02:26

    It's safest to not cast, but convert -- i.e., create a new array and fill it with the values found in the struct, then kill the struct.

    0 讨论(0)
  • 2021-01-20 02:32

    malloc allocates bytes. Why did you choose "2*len" ?

    You could simply use "sizeof":

    int32_t *buffer = malloc(len * sizeof(TwoInt32s));
    /* fill in the buffer */
    write((struct TwoInt32s*)buffer, len);
    

    and as Erik mentioned, it would be a good practice to pack the struct.

    0 讨论(0)
  • 2021-01-20 02:39

    The implementation is free to pad structs - there may be unused bytes in between a and b. It is guaranteed that the first member isn't offset from the beginning of the struct though.

    Typically you manage such layout with a compiler-specific pragma, e.g:

    #pragma pack(push)
    #pragma pack(1)
    struct TwoInt32s
    {
      int32_t a;
      int32_t b;
    };
    #pragma pack(pop)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题