#Structure

1 messages · Page 1 of 1 (latest)

primal socket
#

Can anyone explain why
sizeof(int) = 4
sizeof(char) = 1
but for

{
int i;
char c;
}

sizeof(struct s) = 8

harsh prairieBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

dusk nexus
#

That's because of padding.
You can however remove that by using the __attribute__((__packed__)):

#

;compile

#include <stdio.h>

struct __attribute__((__packed__)) foo {
    int i;
    char c;
} x;

int main() {
    printf("sizeof(x) = %d\n", sizeof(x));
}
vestal quartzBOT
#
Program Output
sizeof(x) = 5
dusk nexus
cobalt lava
#

if you're gonna talk about "removing" padding, should also mention why it exists I think

#

including alignment constraints

dusk nexus
#

I was just gonne give that example, then link to the SO post

cobalt lava
#

fair enough

primal socket
#

@dusk nexus so padding is a bad thing or it can be ignored?

dusk nexus
# primal socket <@137956696210407424> so padding is a bad thing or it can be ignored?

Just ignore it for now.

Padding exists to properly align memory because access to unaligned memory is slower than it is to aligned memory (and some CPU architectures won't even allow unaligned memory access).

The tradeoff when you pack a struct is that each individual struct will consume less memory, however the access to the structs' elements may be slower.

primal socket
#

Kk. Thanks

#

!solved