c - 有没有办法遍历多个结构,比如通过一个数组?

标签 c struct

有没有办法循环遍历结构并在此过程中为其成员赋值?

我不太确定我的问题是否正确,所以我会尝试用代码显示它,这当然是无效的,但希望能作为更好的例子:

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/

相关文章:

c - 即使没有来自用户的输入,字符串也有内容

c++ - 混合 gtk+ 和 c++

c - for 循环 - 为什么打印 12 而不是 3?

arrays - Coldfusion 中的 Foreach() array.each()...数组和结构向后?是什么赋予了?

c - 如何复制结构体指针

c++ - 将字符串指针传递给 C++ 中的结构

c++ - WSASockets 是否能够在不使用管道的情况下获取进程 I/O?

c - 我正在寻找一种在 c 头文件中初始化数组的方法

C#:查找和更改结构数组中的元素

objective-c - Objective-C 中的 Box 自定义结构