简体   繁体   English

如何将一个结构复制到另一个结构的元素数组?

[英]How to copy one structure to array which are element of another structure?

I have Two structure:1)ABC 2)CDE 我有两种结构:1)ABC 2)CDE

typedef struct
{
  unsigned char b[8];
  unsigned char a[12];
  unsigned char c;
} ABC;

ABC sABC;

typedef struct
{
  unsigned char D;
  unsigned char E[22];           
} CDE;

I want to copy Structure ABC in E[22] which is member of CDE structure. 我想在E [22]中复制结构ABC,它是CDE结构的成员。

If anyone know this then how can i do this? 如果有人知道这一点,那我该怎么办?

You could do it with memcpy . 您可以使用memcpy做到这一点。 For instance something like this should work: 例如这样的事情应该工作:

memcpy(&some_CDE_variable.E, &sABC, 22);

But take care that sizeof(ABC) may not be 22 and the elements inside may not be layed out the way you would expect if the compiler decides to add some padding when packing that struct in memory. 但是请注意, sizeof(ABC)可能不为22,并且如果编译器决定在将该结构打包到内存中时决定添加一些填充,则内部元素的布局可能不符合您的期望。 If you're using gcc you may want to check for the packed attribute. 如果您使用的是gcc,则可能要检查packed属性。

you can use memcpy in your case. 您可以使用memcpy。

just use memcpy safely as memcpy replaces memory, it does not append. 只需安全使用memcpy即可,因为memcpy会替换内存,但不会追加。 If you want to use memcpy, your code will need to be a little more complex. 如果要使用memcpy,您的代码将需要稍微复杂一点。

void * memcpy ( void * destination, const void * source, size_t num ); void * memcpy(void *目标,const void *源,size_t num);

also,take care of size here as num will vary on compiler basis because of padding. 同样,请注意此处的大小,因为num会因填充而在编译器的基础上有所不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM