初始化结构的数组,为什么使用结构变量无法正常工作 [英] Initializing an array of structs, why does using struct variables not work
问题描述
我非常新C ..将AP preciate,如果有人可以帮助理解为什么在管路13,14和16 code没有工作,但17-20行的作品。
通过第一个选项(线13,14和16)我得到的错误
错误:初始元素不是常数
这是什么意思?此外,这是否意味着人们不能使用某些类型的变量产生新的变数?
感谢您。
//定义结构有一个良好的
5结构良好{
6字符goodname;
7双磷; //比例开始
8 INT THETA; //平均效用
9 INT西格玛; //错误的方差
10};
11
12 //货物H和L
13结构良好H = {.goodname ='H',P = 0.5,西塔= 100,西格玛= 20};
14结构良好L = {.goodname =L,P = 0.5,西塔= 75,西格玛= 20};
15
16结构好货[2] = {H,L}; // **不工作** // ** **工程
17结构好货[2] = {
18 {.goodname =H,P = 0.5,西塔= 100,西格玛= 20},
19 {.goodname =L,P = 0.5,西塔= 75,西格玛= 20}
20};
H和L是包含数据的存储位置。声明:
结构体好货[2] = {H,L}; // **不工作**
意味着产品应指向H和L,或包含相同的值H和L
无论,复制从H到产品中的数据和L [0]和[1]或修改产品是一个指针数组,作为
结构体好货* [2]; 产品[0] =&放大器; H:
产品[1] =&放大器; L,
I am extremely new to C. Would appreciate if someone can help understand why code in lines 13,14 and 16 does not work, but lines 17-20 works.
With the first option (lines 13, 14 and 16) I get the error
error: initializer element is not constant
What does this mean? Also, does this mean one cannot use variables of certain type to generate new variables?
Thank you.
// Define structure for a good
5 struct good {
6 char goodname;
7 double p; //starting proportion
8 int theta; //average utility
9 int sigma; //variance of error
10 };
11
12 // The goods H and L
13 struct good H = {.goodname = 'H', .p = 0.5, .theta = 100, .sigma = 20};
14 struct good L = {.goodname = 'L', .p = 0.5, .theta = 75, .sigma = 20};
15
16 struct good goods[2] = {H, L}; // **Does not work**
// ** Works**
17 struct good goods[2] = {
18 {.goodname = 'H', .p = 0.5, .theta = 100, .sigma = 20},
19 {.goodname = 'L', .p = 0.5, .theta = 75, .sigma = 20}
20 };
H and L are storage locations that contain data. The statement:
struct good goods[2] = {H, L}; // **Does not work**
implies that goods should point to H and L, or contain the same values as H and L.
Either, copy the data from H and L to goods[0] and [1] or modify goods to be an array of pointers, as:
struct good *goods[2];
goods[0] = &H;
goods[1] = &L;
这篇关于初始化结构的数组,为什么使用结构变量无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!