Copy structure to char array

I am learning C and wondering about structures.

I have

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

Storage requires at least 30 bytes of memory. Is it possible to copy all this data into a char foo[30] variable char foo[30] ? What will be the syntax?

+8
source share
6 answers

You cannot just copy all this because the compiler can arbitrarily decide how to do this. You will need three memcpy calls:

 struct myStruct s; // initialize s memcpy(foo, s.member1, sizeof s.member1); memcpy(foo + sizeof s.member1, s.member2, sizeof s.member2); memcpy(foo + sizeof s.member1 + sizeof s.member2, s.member3, sizeof s.member3); 
+14
source

The size of struct myStruct is equal to sizeof(struct myStruct) and nothing else. It will be at least 30, but it can be any greater value.

You can do it:

 char foo[sizeof(struct myStruct)]; struct myStruct x; /* populate */ memcpy(foo, &x, sizeof x); 
+4
source

According to the standard C (6.2.6. Representations of types)

4 Values ​​stored in objects without a bit field of any other type of object consist of n Γ— CHAR_BIT bits, where n is the size of an object of this type, in bytes. The value can be copied to an object of type unsigned char [n] (for example, using memcpy ); a resultant set of bytes called a value object representation.

So you can just write

 unsigned char foo[sizeof( struct myStruct )]; struct myStruct s = { /*...*/ }; memcpy( foo, &s, sizeof( struct myStruct ) ); 

Note that you can copy data items separately in one array. for instance

 unsigned char foo[30]; struct myStruct s = { /*...*/ }; unsigned char *p = foo; memcpy( p, s.member1, sizeof( s.member1 ) ); memcpy( p += sizeof( s.member1 ), s.member2, sizeof( s.member2 ) ); memcpy( p += sizeof( s.member2 ), s.member3, sizeof( s.member3 ) ); 
+3
source

Yes it is possible.

There are various ways to do this. The following are two simple 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 an array of characters like this, you should be very careful, since the dimensions of the structure are not always what you might think first. In your particular case there can be no problems; but in general, you should at least be aware of the possible fill, alignment, and font size issues that might change the size of your structure.

Hope this helps.

+1
source

you can do the following if you have a myStruct variable called st:

 strcpy(foo, st.member1); strcat(foo, st.member2); strcat(foo, st.member3); 
0
source

Pretty simple with memcpy.

 char foo[30]; struct myStruct s; s.member1 = //some data s.member2 = //some data s.member3 = //some data memcpy(foo, &s, 30); 
0
source

Source: https://habr.com/ru/post/1204936/


All Articles