谁能解释一下原因
all_leds[0].pattern = 3;
和
all_leds[1].pattern = 4;
什么都不做?
#include <stdio.h>
int main(void)
{
struct Led
{
int pin;
int pattern;
};
struct Led led_1 = {1, 1};
struct Led led_2 = {2, 2};
printf("%d\n", led_1.pattern); // prints 1
printf("%d\n", led_2.pattern); // prints 2
struct Led all_leds[2];
all_leds[0] = led_1;
all_leds[1] = led_2;
printf("%d\n", led_1.pattern); // prints 1
printf("%d\n", led_2.pattern); // prints 2
all_leds[0].pattern = 3;
all_leds[1].pattern = 4;
printf("%d\n", led_1.pattern); // prints 1 ????
printf("%d\n", led_2.pattern); // prints 2 ????
return 0;
}
最佳答案
Led
是值类型(与 C 中的所有类型一样;它没有像 C++ 那样的引用类型)所以当您说 all_leds[0] = led_1;
您正在复制led_1
中的结构值到all_leds
的第一个元素中。在这一行之后,all_leds[0]
和 led_1
仍然是独立的值,彼此没有任何联系。修改一个不会修改另一个。
相反,您可以使用指向 Led
值的指针填充 all_leds
。
struct Led * all_leds[2] = { &led_1, &led_2 };
// ...
all_leds[0]->pattern = 3;
all_leds[1]->pattern = 4;
关于带有结构的 C 数组 - 不能更改变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32143644/