如何迭代复合文字数组

How to iterate over the compound literal array

如何遍历复合文字数组以便打印 book_idvalue

#include <stdio.h>
#include <string.h>

typedef struct {
    int book_id;
    char value;
} BookCode;

typedef struct {
    BookCode *codes;
} Books;

int main() {
    Books MyBooks[] = { 
        (BookCode[]){ {1, 'a'},{2, 'b'} },
        (BookCode[]){ {1, 'd'},{2, 'c'}, {3, 'f'} },
    };  

    int i,j;
    int n1 = sizeof(MyBooks)/sizeof(MyBooks[0]);
    for(i = 0; i < n1; i++){
        printf("%d\n", i); 
        // how to iterate over compound literal array?
    }   
    return 0;
}

how to iterate over compound literal array?

你不能。

至少在不提供有关两个 BookCode 数组携带的元素数量的 附加 信息的情况下,即 2 和 3。后面的信息是 lost 通过将两个数组分配给 MyBooks 的指针类型元素。在 运行 时间内无法再计算。

您可以做的是定义一个哨兵值,并在每个 BookCode 数组的末尾添加一个诸如停止元素的实例。这样每个数组的大小都可以在 运行 时间内(重新)计算。

例如,可以如下所示完成:

#include <stdio.h>
#include <string.h>

typedef struct
{
  int book_id;
  char value;
} BookCode;

#define BOOKCODE_STOPPER {-1, '[=10=]'}
static const BookCode BookCodeStopper = BOOKCODE_STOPPER;

typedef struct
{
  BookCode *codes;
} Books;

size_t get_codes_count(Books * books)
{
  BookCode * bc = books->codes;

  while (bc->book_id != BookCodeStopper.book_id
      && bc->value != BookCodeStopper.value)
  /* doing "while (memcmp(bc, &BookCodeStopper, sizeof BookCodeStopper)" might be faster. */
  {
    ++bc;
  }

  return bc - books->codes;
}

int main(void)
{
  Books books[] = {
    {(BookCode[]) {{1, 'a'}, {2, 'b'}, BOOKCODE_STOPPER}},
    {(BookCode[]) {{1, 'd'}, {2, 'c'}, {3, 'f'}, BOOKCODE_STOPPER}}
  };

  size_t n1 = sizeof books / sizeof books[0];
  for (size_t i = 0; i < n1; ++i)
  {
    printf("%zu\n", i);

    size_t s = get_codes_count(books + i);
    for (size_t j = 0; j < s; ++j)
    {
      printf("Book code %zu: id=%d, value=%c\n", j, books[i].codes[j].book_id,
          books[i].codes[j].value);
    }
  }

  return 0;
}

这种方法意味着至少一种可能的书籍代码组合永远不会出现。在上面的示例中,我为此选择了 {-1, '[=14=]'}