Copy struct into char array

前端 未结 6 2034
面向向阳花
面向向阳花 2020-12-31 15:41

I am learning C and have a question about structs.

I have a

struct myStruct {
    char member1[16];
    char member2[10];
    char member3[4];
};         


        
6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-31 16:01

    Yes, it is possible.

    There are different ways you can go about doing this. Below are the two simplest methods.

    struct myStruct  myVar;
    
    /* Initialize myVar */
    ...
    
    memcpy (foo, &myVar, sizeof (myStruct));
    

    Or if you are dealing with a pointer ...

    struct myStruct *  myVarPtr;
    
    /* Initialize myVarPtr */
    ...
    
    memcpy (foo, myVarPtr, sizeof (myStruct));
    

    Note that when copying a structure to/from a character array like this, you have to be very careful as structure sizes are not always what you might first think. In your particular case, there might not be any issues; but in general, you should at least be aware of potential padding, alignment and type size issues that may change the size of your structure.

    Hope this helps.

提交回复
热议问题