简体   繁体   English

在结构的灵活成员数组中打印结构成员的地址

[英]Printing address of struct members in flexible member array of structs

I have a struct which contains a flexible member array: 我有一个包含弹性成员数组的结构:

typedef struct bar {
  uint8_t  bar_a;
  uint16_t bar_b;
} bar_t;

typedef struct foo {
  uint16_t foo_a;
  uint_8_t n_bars;
  bar_t    *bars[];
} foo_t;

I'm trying to use foo and bar as data structures to copy data over to uint8_t buffer[50] . 我正在尝试使用foobar作为数据结构来将数据复制到uint8_t buffer[50]

#define NUMBER_OF_BARS 1;
static uint8_t buffer[50];

static foo_t *
copy_to_buf(void *buf)
{
  int i;
  foo_t *foo = (foo_t *)buf;
  bar_t bar;

  /* Set foo_a */
  foo->foo_a = 1;
  foo->n_bars = NUMBER_OF_BARS;
  /* Set bars */
  for(i=0; i < foo->n_bars; i++) {
    bar.bar_a = 0xFF;
    bar.bar_b = 1234;
    memcpy(&foo->bars[i], &bar, sizeof(bar_t));
  }
  return foo;
}

int main()
{
  int i;
  foo_t *foo = copy_to_buf(&buffer);
  printf("foo ... [%p %p %p %p]\n", 
         &foo, &foo->foo_a, &foo->n_bars &foo->bars);
  for(i=0; i < foo->n_bars; i++) {
    printf("bar ... [%p %p %p]\n", 
           &foo->bars[i], &foo->bars[i]->bar_a, &foo->bars[i]->bar_b);
  }
  return 0;
}

Now I would have expected this to print the following (ie a contiguous block of memory): 现在,我期望它可以打印以下内容(即连续的内存块):

foo ... [0x1f92 0x1f92 0x1f94 0x1f95]
bar ... [0x1f95 0x1f95 0x1f96]

Instead, I'm getting the following: 相反,我得到以下信息:

foo ... [0x1f92 0x1f92 0x1f94 0x1f95]
bar ... [0x1f95 0x0 0x1]

What am I doing wrong? 我究竟做错了什么?

Since foo.bars is an array of pointers, you need to allocate memory for the objects they point to, and then copy to that memory. 由于foo.bars是一个指针数组,因此您需要为其所指向的对象分配内存,然后将其复制到该内存中。

static foo_t *
copy_to_buf(void *buf)
{
  int i;
  foo_t *foo = (foo_t *)buf;
  bar_t bar;

  /* Set foo_a */
  foo->foo_a = 1;
  foo->n_bars = NUMBER_OF_BARS;
  /* Set bars */
  for(i=0; i < foo->n_bars; i++) {
    bar.bar_a = 0xFF;
    bar.bar_b = 1234;
    foo->bars[i] = malloc(sizeof(bar_t));
    memcpy(foo->bars[i], &bar, sizeof(bar_t));
  }
  return foo;
}

Or you could declare it as an array of structures instead of pointers. 或者,您可以将其声明为结构数组而不是指针。

typedef struct foo {
  uint16_t foo_a;
  uint_8_t n_bars;
  bar_t    bars[];
} foo_t;

and change how you access them in main() 并更改您在main()访问它们的方式

int main()
{
  int i;
  foo_t *foo = copy_to_buf(&buffer);
  printf("foo ... [%p %p %p %p]\n", 
         &foo, &foo->foo_a, &foo->n_bars &foo->bars);
  for(i=0; i < foo->n_bars; i++) {
    printf("bar ... [%p %p %p]\n", 
           &foo->bars[i], &foo->bars[i].bar_a, &foo->bars[i].bar_b);
  }
  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM