[英]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. 我正在使用offsetof()获取所有元素的偏移量。
How can I copy values to bb[5] using memcpy, offsetof() and knowing address of the base struct? 如何使用memcpy,offsetof()并知道基本结构的地址将值复制到bb [5]?
I tried this: 我尝试了这个:
It goes from 0-4 从0-4开始
memcpy((base_address_of_st_L3 + offset + sizeof(int)*i ), &int_data, sizeof(int))
How can I copy values to bb[5] using memcpy, offsetof() and knowing address of the base struct? 如何使用memcpy,offsetof()并知道基本结构的地址将值复制到bb [5]?
The following code snipped declares the structure and an array of 5 int
s. 以下代码片段声明了该结构和5个int
的数组。 Then using memcpy
it copies the int's
into the structure's bb
member. 然后使用memcpy
将int's
复制到结构的bb
成员中。 I cast the pointer to void*
to try to "generalize" the example. 我将指针转换为void*
以尝试“概括”该示例。
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. 请注意,对void*
指针执行指针算术是无效的。 That's why a cast to char*
is needed. 这就是为什么需要强制转换为char*
的原因。
If I understand your question, you wish to copy and integer to a integer array of size 5? 如果我理解您的问题,您是否希望将整数复制并复制为大小为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. 当然, bb
仍将剩下四个不会初始化的整数。
Or did you mean that int_data
is also an array of five integers? 还是您是说int_data
也是由五个整数组成的数组?
{
int i;
[... snipped ...]
for(i = 0; i < 5; i++)
{
((st_L3*)base_address_of_st_L3)->bb[i] = int_data[i];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.