размер структуры в C [дубликат]

import urllib2
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request('http://example.org', data='your_put_data')
request.add_header('Content-Type', 'your/contenttype')
request.get_method = lambda: 'PUT'
url = opener.open(request)
44
задан Community 23 May 2017 в 12:10
поделиться

4 ответа

The compiler may add padding for alignment requirements. Note that this applies not only to padding between the fields of a struct, but also may apply to the end of the struct (so that arrays of the structure type will have each element properly aligned).

For example:

struct foo_t {
    int x;
    char c;
};

Even though the c field doesn't need padding, the struct will generally have a sizeof(struct foo_t) == 8 (on a 32-bit system - rather a system with a 32-bit int type) because there will need to be 3 bytes of padding after the c field.

Note that the padding might not be required by the system (like x86 or Cortex M3) but compilers might still add it for performance reasons.

61
ответ дан 26 November 2019 в 22:12
поделиться

As mentioned, the C compiler will add padding for alignment requirements. These requirements often have to do with the memory subsystem. Some types of computers can only access memory lined up to some 'nice' value, like 4 bytes. This is often the same as the word length. Thus, the C compiler may align fields in your structure to this value to make them easier to access (e.g., 4 byte values should be 4 byte aligned) Further, it may pad the bottom of the structure to line up data which follows the structure. I believe there are other reasons as well. More info can be found at this wikipedia page.

3
ответ дан 26 November 2019 в 22:12
поделиться

Your default alignment is probably 4 bytes. Either the 30 byte element got 32, or the structure as a whole was rounded up to the next 4 byte interval.

2
ответ дан 26 November 2019 в 22:12
поделиться

Выравнивание по 6 байтам не является странным, потому что оно выравнивается по адресам, кратным 4.

Таким образом, в основном у вас есть 34 байта в вашей структуре, и следующая структура должна быть размещена по адресу , что кратно 4. Ближайшее значение после 34 - 36. И эта область заполнения учитывается в размере структуры.

1
ответ дан 26 November 2019 в 22:12
поделиться
Другие вопросы по тегам:

Похожие вопросы: