Знам, че има padding in struct (пример от тази публикация)
struct A -->8 bytes
{
char c;
char d;
//2 padding here
int i;
};
struct B -->12 bytes
{
char c;
//3 padding here
int i;
char d;
//3 padding here
};
Сега не разбирам следния пример:
typedef struct { -->**shouldn't it be 12 bytes**
int a;
char *str;
} TestS;
TestS s;
int main(int argc, char *argv[]) {
printf("An int is %lu bytes\n", sizeof( int )); -->4
printf("A Char * is %lu bytes\n", sizeof( char *)); -->8
printf("A double is %lu bytes\n", sizeof( double )); -->8
printf("A struct is %lu bytes\n", sizeof s); -->why 16?
return 0;
}
Първо си помислих, че може да подравнява към 8*N байта (защото използвам ubuntu-64), така че опитвам повече структури.
typedef struct {
int i;
char *str;
} stru_12;
typedef struct {
int i;
char *str;
char c;
} stru_13;
typedef struct {
int i;
char str[7];
} stru_11;
typedef struct {
char *str;
double d;
} stru_16;
stru_12 test12;
stru_13 test13;
stru_11 test11;
stru_16 test16;
int main (int argc, char *argv[]) {
printf("A test12 is %lu bytes, address is %p\n", sizeof test12, &test12);
printf("A test13 is %lu bytes, address is %p\n", sizeof test13, &test13);
printf("A test11 is %lu bytes, address is %p\n", sizeof test11, &test11);
printf("A test16 is %lu bytes, address is %p\n", sizeof test16, &test16);
}
Резултат:
Test12 е 16 байта, адресът е 0x601060
Тест13 е 24 байта, адресът е 0x601090
Тест11 е 12 байта, адресът е 0x601080
Test16 е 16 байта, адресът е 0x601070
Съжалявам, че се забавих толкова дълго.
Въпросът ми е:
Защо test12 (int + char*) е 16 байта, а test13 (int + char * + char) е 24? (изглежда, че 8*N е предпочитан, но 12 байта са разрешени)
Защо разликите в адресите на структурите са 16 адресна единица (повече подложка?)?
За ваша употреба:
cache_alignment: 64
размери на адресите: 36 бита физически, 48 бита виртуални
Ubuntu 14.04.1 LTS x86_64
sizeof(struct stru_12)
и т.н.? По-малко визуално безпорядък. - person Kerrek SB   schedule 31.07.2014