staleobject26
staleobject26

Reputation: 11

How do I fill an array inside a struct using offsetof() and pointers in C

I have a struct

typedef struct _st_L3 {
   int e;
   int f;
   int bb[5];
   int g;
} st_L3;

and I am using offsetof() to get offset of all the elements.

How can I copy values to bb[5] using memcpy, offsetof() and knowing address of the base struct?

I tried this:

It goes from 0-4

memcpy((base_address_of_st_L3 + offset + sizeof(int)*i ), &int_data, sizeof(int))

Upvotes: 0

Views: 439

Answers (2)

MartinVeronneau
MartinVeronneau

Reputation: 1306

If I understand your question, you wish to copy and integer to a integer array of size 5?

You can do it this way :

((st_L3*)base_address_of_st_L3)->bb[0] = int_data;

Of course, bb will still have four integers left that won't be initialized.

Or did you mean that int_data is also an array of five integers?

{
  int i;

[... snipped ...]

  for(i = 0; i < 5; i++)
  {
    ((st_L3*)base_address_of_st_L3)->bb[i] = int_data[i];
  }
}

Upvotes: 1

KamilCuk
KamilCuk

Reputation: 140980

How can I copy values to bb[5] using memcpy, offsetof() and knowing address of the base struct?

The following code snipped declares the structure and an array of 5 ints. Then using memcpy it copies the int's into the structure's bb member. I cast the pointer to void* to try to "generalize" the example.

int main() {
     st_L3 var;
     int array[5]; // int_data
     void *pnt = &var; // base_address_of_st_L3 

     // using operator `[]`
     memcpy(&((char*)pnt)[offsetof(st_L3, bb)], array, sizeof(int) * 5);

     // using pointer arithmetics
     memcpy(((char*)pnt) + offsetof(st_L3, bb), array, sizeof(int) * 5);

     // one variable at a time
     for (int i = 0; i < 5; ++i) {
         memcpy(&((char*)pnt)[offsetof(st_L3, bb) + i], &array[i], sizeof(int));
     }
}

Note that doing pointer arithmetics on void* pointers is invalid. That's why a cast to char* is needed.

Upvotes: 1

Related Questions