gpt4 book ai didi

c - 使数组显示错误值的结构

转载 作者:行者123 更新时间:2023-12-04 10:15:46 25 4
gpt4 key购买 nike

有谁知道为什么成员Node_ptr next;让数组poly[1]poly[2]的元素显示错误的值(value)?如果我从结构 (struct node) 中删除 Node_ptr next;,我就能获得索引 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;
}

最佳答案

引用 C11,第 6.7.9 章,(强调我的)

Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union. [...]

所以,基本上,在初始化中

struct node p1_terms[] = {10, 1000, 5, 14, 1, 0};

数组大小为 2。它创建了 struct node 的两个元素,因此访问 p1_terms[2] 是越界访问,调用 undefined behavior .

也就是说,初始化按顺序初始化结构元素,这意味着,对于上述情况,成员值将像

p1_terms[0].coef = 10;
p1_terms[0].exp= 1000;
p1_terms[0].next= 5; // see here....

这肯定不是您想要的。您需要像这样使用初始化列表

struct node p1_terms[] = {{10, 1000}, {5, 14}, {1, 0}};

避免 next 被初始化。

相关的,来自同一章节

If the aggregate or union contains elements or members that are aggregates or unions, these rules apply recursively to the subaggregates or contained unions. If the initializer of a subaggregate or contained union begins with a left brace, the initializers enclosed by that brace and its matching right brace initialize the elements or members of the subaggregate or the contained union. [...]

关于c - 使数组显示错误值的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37421076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com