Reputation: 16627
I read about __packed__
from here and, I understood that when __packed__
is used in a struct
or union
, it means that the member variables are placed in such a way to minimize the memory required to store the struct
or union
.
Now, consider the structures in the following code. They contain same elements (same type
, same variable names and placed in the same order). The difference is, one is __packed__
and the other is not.
#include <stdio.h>
int main(void)
{
typedef struct unpacked_struct {
char c;
int i;
float f;
double d;
}ups;
typedef struct __attribute__ ((__packed__)) packed_struct {
char c;
int i;
float f;
double d;
}ps;
printf("sizeof(my_unpacked_struct) : %d \n", sizeof(ups));
printf("sizeof(my_packed_struct) : %d \n", sizeof(ps));
ups ups1 = init_ups();
ps ps1;
return 0;
}
Is there a way where we can copy unpacked structure ups1
into packed structure ps1
without doing a member-variable-wise-copy
? Is there something like memcpy()
that is applicable here?
Upvotes: 3
Views: 1931
Reputation: 70979
Without detailed knowlegde of the differences of the memory layout of the two structures: No.
Upvotes: 1
Reputation: 118720
I'm afraid you've just gotta write it out. Nothing in standard C (or any standard I know of) will do this for you. Write it once and never think about it again.
ps ups_to_ps(ups ups) {
return (ps) {
.c = ups.c,
.i = ups.i,
.f = ups.f,
.d = ups.d,
};
}
Upvotes: 7