Cast a struct of ints to an array of ints

后端 未结 4 552
日久生厌
日久生厌 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: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.

提交回复
热议问题