I have the following struct:
typedef struct P{
int age;
char gender;
int weight;
}Person;
I'm working with blocks of data. So all of my data are inside char Person_Data[50];
The expected outcome is to move the data from Person_Data
to my struct. In order to achieve this I'm using memcpy, having in mind that inside Person_Data
I can store either int or char(or anything else I might add).
I wrote a code for a testable example:
char Person_Data[50];
size_t offset = 0;
memset(Person_Data + offset, 24, sizeof(int));
offset += sizeof(int);
memset(Person_Data + offset, 'M', sizeof(char));
offset += sizeof(char);
memset(Person_Data + offset, 55, sizeof(int));
printf("Age = %d, Gender = %c, weight = %d\n", *(Person_Data), *(Person_Data + sizeof(int)), *(Person_Data + sizeof(int) + sizeof(char)));
Until this point we can see that the data inside my string are passed correctly, maintaining their type. (I guess from what I have read in various books).
Now I pass the data from Person_Data
to my struct:
Person *Person1 = malloc(sizeof(Person));
offset = 0;
memcpy(&Person1->age, Person_Data + offset, sizeof(int));
offset += sizeof(int);
memcpy(&Person1->gender, Person_Data + offset, sizeof(char));
offset += sizeof(char);
memcpy(&Person1->weight, Person_Data + offset, sizeof(int));
printf("Age = %d, Gender = %c, weight = %d\n", Person1->age, Person1->gender, Person1->weight);
As we can see the output of the above code is
Age = 24, Gender = M, weight = 55
Age = 404232216, Gender = M, weight = 926365495
So, the 2 int
have not passed correctly into the struct.
That got me wondering and I tried this with memset
like this:
memset(&Person1->age, *(Person_Data + offset), sizeof(int));
But it didn't work also. So the last attempt was to pass the int like this:
Person1->age = *(Person_Data);
After doing this I saw that the age was passed correctly. My thought is whether this is correct.
How the "=" operator knows how many bytes to pass?
Shouldn't memcpy/memset do the work since the third argument is how many bytes to copy?
Thank you.
printf
.offsetof
(<stddef.h>
).