gpt4 book ai didi

c - 如何迭代复合文字数组

转载 作者:太空宇宙 更新时间:2023-11-03 23:23:34 33 4
gpt4 key购买 nike

如何遍历复合文字数组以便打印 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。后面的信息丢失了 通过将两个数组分配给 MyBooks 的指针类型元素。在运行时无法再计算。

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

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

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

关于c - 如何迭代复合文字数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32926513/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com