【问题标题】:getting address of the structure padded bytes获取结构填充字节的地址
【发布时间】:2016-01-13 17:35:09
【问题描述】:

我很想知道结构填充中填充字节中包含的值。

所以我写了下面的代码,但是增加指针会指向下一个结构成员。我们如何访问填充的内存位置?

#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;
}

【问题讨论】:

  • 我会使用char*
  • 谢谢,这就是我想要的。填充字节中的默认值是什么?
  • @KlasLindbäck ... 指向&amp;a 并迭代sizeof(a) 步骤。
  • 是的,根据设计/规范,将指向类型的指针递增会使指针中的内存地址增加 sizeof(type)。 char* pB = &a.b;和 char* pC = (char*)&a.c;然后当 pB

标签: c struct padding


【解决方案1】:

您可以使用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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-07
    • 2016-12-09
    • 2016-01-09
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    相关资源
    最近更新 更多