如何迭代复合文字数组

时间:2015-10-03 19:18:00

标签: c arrays size sizeof compound-literals

如何迭代复合文字数组,以便打印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;
}

1 个答案:

答案 0 :(得分:2)

  

如何迭代复合文字数组?

你做不到。

至少没有提供关于两个BookCode数组携带的元素数量的附加信息,即2和3.后面的信息丢失通过将两个数组分配给MyBooks的指针类型元素。在运行期间不能再计算它。

你可以做的是定义一个sentinel值,并在每个BookCode数组的末尾添加一个诸如stop元素的实例。这样,可以在运行时(重新)计算每个阵列的大小。

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

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

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

#define BOOKCODE_STOPPER {-1, '\0'}
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, '\0'}