Reputation: 7494
I have the following structure:
typdef struct {
char a[4];
int b;
char c;
int d;
} varT; // Total size is 13 bytes, without padding
which shows the desired memory layout in RAM for variables of type 'varT';
Which means that in RAM, the following layout of data is required:
From address 1000 to 1013 (excluding 1013):
[ field 'a', 4 bytes | field 'b', 4 bytes | field 'c', 1 byte | field 'd', 4 bytes ]
From address 1013 to 1026 (excluding 1026):
[ field 'a', 4 bytes | field 'b', 4 bytes | field 'c', 1 byte | field 'd', 4 bytes ], ...
But the compiler adds padding of 3 bytes between field c
to field d
.
How would you recommend to bypass that padding in order to conveniently deal with this type of variable, that is stored in RAM?
What I'd like to do is similar to the following:
varT var;
varT *list[5];
var.a[0] = 'A'; var.a[1] = 'B'; var.a[2] = 'C'; var.a[3] = 'D';
var.b = 9876;
var.c = 'X';
var.d = 1234;
memcpy((void*)(list), (void*)(&var), 13);
var.a[0] = 'E'; var.a[1] = 'F'; var.a[2] = 'G'; var.a[3] = 'H';
var.b = 6543;
var.c = 'V';
var.d = 8887;
memcpy((void*)(list + 13), (void*)(&var), 13);
But this is not possible due to the padding that the compiler adds to the struct.
Upvotes: 0
Views: 77
Reputation:
Why don't you write sane, idiomatic C instead, for a change:
typedef struct {
char a[4];
int b;
char c;
int d;
} varT;
Can be easily handled like this:
varT vlist[n];
varT x = {.a = {'A', 'B', 'C', 'D'}, .b = 9876, .c = 'X', .d = 1234};
vlist[0] = x;
struct
s can simply be assigned to. Also, this avoids your errors with indirection.
Upvotes: 0
Reputation: 61910
I think one of these could be done.
gcc
, __attribute__((packed))
, __attribute__((aligned))
Some notes. Do not use hard coded structure size, also do not use sizeof
to compute the size for this kind of applications where you are copying a structure to an array which may be used to communicate to another machine through a network or written to a file which can be loaded later by another binary. On different systems the same code can generate different padding and therefore loading the stored data from the array as you have shown and also by transferring the array through network like this can go real bad. This is because the two binaries communicating can have different padding amount resulting in a different layout which will break things in a pretty bad way and often very difficult to debug.
On the other hand if you are just copying structure to structure then this may work, but for that the =
does the work.
Upvotes: 3
Reputation: 8982
The code should be independent on such padding. So use sizeof(varT)
instead of 13
.
Upvotes: 1