Модераторы: Daevaorn
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Использование sizeof 
:(
    Опции темы
GuManOiD
  Дата 20.9.2005, 18:09 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 79
Регистрация: 12.9.2005

Репутация: нет
Всего: нет



Вот есть такая структура:
Код

typedef struct list_element {
    char info[10];
    list_element *next;
} lst;


Мне надо узнать сколько байт она занимает(1),
по какойто причине
Код

printf("%i",sizeof(lst));

Выводит 16!!, но 10 чаров + 1 указатель = 14 БАЙТ!
Кто знает в чем проблема, отзовитесь!
PM MAIL   Вверх
_hunter
Дата 20.9.2005, 18:35 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Участник Клуба
Сообщений: 8564
Регистрация: 24.6.2003
Где: Europe::Ukraine:: Kiev

Репутация: 16
Всего: 98



выравнивание в 1 байт поставь


--------------------
Tempora mutantur, et nos mutamur in illis...
PM ICQ   Вверх
GuManOiD
Дата 20.9.2005, 19:31 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 79
Регистрация: 12.9.2005

Репутация: нет
Всего: нет



Цитата(_hunter @ 20.9.2005, 18:35)
выравнивание в 1 байт поставь

А как енто сделать???

Добавлено @ 19:31
smile
PM MAIL   Вверх
Дрон
Дата 20.9.2005, 19:42 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Java-ненавистник :)
****


Профиль
Группа: Участник Клуба
Сообщений: 3179
Регистрация: 29.12.2002
Где: Санкт-Петербург

Репутация: 10
Всего: 93



Цитата(GuManOiD @ 20.9.2005, 20:31)
А как енто сделать???

Видишь вверху страницы текстовое поле, рядом с которым написано "Поиск:"?

Введи туда слово "выравнивание", нажми кнопочку "Go" и посмотри на результаты.

Это сообщение отредактировал(а) Дрон - 20.9.2005, 19:45


--------------------
Да. Именно так.
PM   Вверх
Nastya
Дата 23.9.2005, 12:31 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Комодератор
Сообщений: 1287
Регистрация: 27.3.2002
Где: Мариуполь

Репутация: 5
Всего: 44



#pragma pack(push, 1)
Цитата

#pragma pack( [ show ] | [ push | pop ] [, identifier ] , n  )
Specifies packing alignment for structure, union, and class members. pack gives control at the data-declaration level. This differs from compiler option /Zp, which only provides module-level control. pack takes effect at the first struct, union, or class declaration after the pragma is seen; pack has no effect on definitions. Calling pack with no arguments sets n to its default value. This is equivalent to compiler option /Zp8.

show (optional)
Displays the current byte value for packing alignment. The value is displayed by means of a warning message.
push (optional)
Puts a specified packing alignment value, n, on the internal compiler stack, and sets the current packing alignment value to n. If n is not specified, the current packing alignment value is pushed.
pop (optional)
Removes the record from the top of the internal compiler stack. If n is not specified with pop, then the packing value associated with the resulting record on the top of the stack is the new packing alignment value. If n is specified, for example, #pragma pack(pop, 16), n becomes the new packing alignment value. If you pop with identifier, for example, #pragma pack(pop, r1), then all records on the stack are popped until the record with identifier is found, and that record is popped and the packing value associated with the resulting record on the top of is the stack the new packing alignment value. If you pop with an identifier that is not found in any record on the stack, then the pop is ignored.
identifier (optional)
When used with push, assigns a name to the record on the internal compiler stack. When used with pop, pops records off the internal stack until identifier is removed; if identifier is not found on the internal stack, nothing is popped.
n (optional)
Specifies the value, in bytes, to be used for packing. The default value for n is 8. Valid values are 1, 2, 4, 8, and 16. The alignment of a member will be on a boundary that is either a multiple of n or a multiple of the size of the member, whichever is smaller.
Consider the following example,

struct s
{
  int i;      // aligned on byte boundary 0, size is 4
  short j;      // aligned on byte boundary 4, size is 2
  double k;  // aligned on byte boundary 8, size is 8
}
n can be used with push or pop for setting a particular stack value, or alone for setting the current value used by the compiler.

For more information on modifying alignment, see:

__alignof
align
Example
// pragma_directives_pack.cpp
// compile with: /W1 /LD
#pragma pack()  // n defaults to 8; equivalent to /Zp8
#pragma pack(show)  // C4810
#pragma pack(4)  // n=4
#pragma pack(show)  // C4810
#pragma pack(push, r1, 16)  // n=16, pushed to stack
#pragma pack(show)  // C4810
#pragma pack(pop, r1, 2)  // n=2 , stack popped
#pragma pack(show)  // C4810
See Also
Pragma Directives






--------------------
Что бы понять рекурсию, надо понять рекурсию

"Профессионал - это человек сделавший все возможные ошибки в очень узкой области". Н.Бор
PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "С++:Общие вопросы"
Earnest Daevaorn

Добро пожаловать!

  • Черновик стандарта C++ (за октябрь 2005) можно скачать с этого сайта. Прямая ссылка на файл черновика(4.4мб).
  • Черновик стандарта C (за сентябрь 2005) можно скачать с этого сайта. Прямая ссылка на файл черновика (3.4мб).
  • Прежде чем задать вопрос, прочтите это и/или это!
  • Здесь хранится весь мировой запас ссылок на документы, связанные с C++ :)
  • Не брезгуйте пользоваться тегами [code=cpp][/code].
  • Пожалуйста, не просите написать за вас программы в этом разделе - для этого существует "Центр Помощи".
  • C++ FAQ

Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, Earnest Daevaorn

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | C/C++: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.0442 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.