2015-10-15 5 views
1

Мне было любопытно узнать значения, содержащиеся в заполненных байтах в прокладке структуры.Получение адреса структуры проложенных байтов

Итак, я написал следующий код, но приращение указателя укажет на следующий элемент структуры. Как мы можем получить доступ к дополнительным ячейкам памяти?

#include <stdio.h> 

struct /* __attribute__((__packed__))*/ test{ 
     int a; 
     char b; 
     int c; 
}; 

main(){ 
     struct test a; 
     a.a = 10; 
     a.b = 's'; 
     a.c = 15; 

     printf("%d\n",sizeof(a)); 
     printf("address of first int is: %p \n",(void *)&a.a); 
     printf("address of the first char is : %p\n",(void *)&a.b); 
     printf("address of the second int is : %p\n",(void *)&a.c); 

     printf("the value of char is: %c\n", a.b); 

     int *p; 
     p = (void *) &a.b; 
     printf("%p\n",p); 
     p++; 
     printf("the value in the padded place is: %d\n",*p); 

     return 0; 
} 
+1

Я хотел бы использовать '' символ *. –

+0

Спасибо, что я хотел. Каковы будут значения по умолчанию в заполненных байтах? – Shashank

+0

@ KlasLindbäck ... который указывает на '& a' и выполняет итерации' sizeof (a) 'шагов. –

ответ

4

Вы можете использовать const unsigned char *:

void print_hex(const void *data, size_t size) 
{ 
    const unsigned char *src = data; 
    while (size > 0) 
    { 
    printf("%02x ", *src++); 
    --size; 
    } 
    printf("\n"); 
} 

Использование так:

struct test a = { 10, 's', 15 }; 
print_hex(&a, sizeof a); 
+0

Удивительный !!!!!!! –