有没有办法循环遍历结构并在此过程中为其成员赋值?
我不太确定我的问题是否正确,所以我会尝试用代码显示它,这当然是无效的,但希望能作为更好的例子:
struct example {
int x;
/* ... */
};
struct example s1;
struct example s2;
int *structs[] = {
s1.x,
s2.x
};
int main(void) {
for (int i = 0; i < 2; i++) {
*structs[i] = i;
}
return 0;
}
基本上,我需要自动执行为多个结构赋值的过程,但我不知道如何操作。这在 C 中甚至可能吗?
最佳答案
如果你修复了一堆琐碎的语法错误,你可以想出:
struct example
{
int x;
/* ... */
};
struct example s1;
struct example s2;
int *structs[] = { &s1.x, &s2.x };
int main(void)
{
for (int i = 0; i < 2; i++)
{
*structs[i] = i;
}
return 0;
}
或者,您可以使用指向结构的指针数组:
struct example
{
int x;
/* ... */
};
struct example s1;
struct example s2;
struct example *examples[] = { &s1, &s2 };
enum { NUM_EXAMPLES = sizeof(examples) / sizeof(examples[0]) };
int main(void)
{
for (int i = 0; i < NUM_EXAMPLES; i++)
{
examples[i]->x = i;
// ...
}
return 0;
}
都可以编译——都可以。
关于c - 有没有办法遍历多个结构,比如通过一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57244401/