Я знаю, что есть заполнение в структуре (пример из этого сообщения)
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
Test13 - 24 байта, адрес 0x601090
Test11 - 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