Ped*_*nho 2 c arrays structure initialization
有谁知道为什么成员Node_ptr next;生成数组的元素poly[1]并poly[2]显示错误的值?如果我Node_ptr next;从结构(struct node)中删除 ,我能够获得索引1和2的正确值.
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct node *Node_ptr;
struct node {
int coef;
int exp;
Node_ptr next;
};
int main()
{
struct node p1_terms[] = {10, 1000, 5, 14, 1, 0};
struct node p2_terms[] = {3, 1990, 2, 1492, 11, 5};
struct node poly[20];
poly[0] = p1_terms[0];
poly[1] = p1_terms[1];
poly[2] = p1_terms[2];
printf("Your polynomials are: \n%dx^%d+%dx^%d+%dx^%d", poly[0].coef, poly[0].exp, poly[1].coef, poly[1].exp, poly[2].coef, poly[2].exp);
int siz = sizeof(poly);
printf("\n\nSize of the array: %d bytes \n",siz);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
引用C11,章节§6.7.9,(强调我的)
每个大括号括起的初始化列表都有一个关联的当前对象.当没有指定时,根据当前对象的类型按顺序初始化当前对象的子对象:增加下标顺序的数组元素,声明顺序中的结构成员,以及union的第一个命名成员.[...]
所以,基本上,在初始化
struct node p1_terms[] = {10, 1000, 5, 14, 1, 0};
Run Code Online (Sandbox Code Playgroud)
数组大小为2.它创建两个元素,struct node因此访问p1_terms[2]是超出限制的访问,调用未定义的行为.
也就是说,初始化按顺序初始化结构元素,这意味着,对于上述情况,成员值将是
p1_terms[0].coef = 10;
p1_terms[0].exp= 1000;
p1_terms[0].next= 5; // see here....
Run Code Online (Sandbox Code Playgroud)
这肯定不是你想要的.您需要使用初始化列表
struct node p1_terms[] = {{10, 1000}, {5, 14}, {1, 0}};
Run Code Online (Sandbox Code Playgroud)
避免next初始化.
相关,来自同一章节
如果聚合或联合包含聚合或联合的元素或成员,则这些规则将递归地应用于子聚合或包含的联合.如果子集合或包含的并集的初始值设定项以左括号开头,则由该括号括起的初始值设定项及其匹配的右括号初始化子集合或所包含的并集的元素或成员.[...]
| 归档时间: |
|
| 查看次数: |
78 次 |
| 最近记录: |