c - 尝试通过链表读取数组时得到错误的整数

标签 c arrays pointers struct linked-list

我一直在尝试创建一个程序,该程序将通过链表读取固定数组。每当我运行我的代码时,程序都会给我一个明显不准确的数字,并且不会遍历数组。对我做错了什么有什么建议吗?

#include <stdio.h>
#include <stdlib.h>

struct number
{
int array[10];
struct number *next;
};

int main()
{

    struct number array[10] = {0, 10, 20, 30, 40, 50, 60, 70, 80, 90};

    struct number *head = 0;
    struct number *tail = 90;

    array[0].next = &array[1];
    array[1].next = &array[2];
    array[2].next = &array[3];
    array[3].next = &array[4];
    array[4].next = &array[5];
    array[5].next = &array[6];
    array[6].next = &array[7];
    array[7].next = &array[8];
    array[8].next = &array[9];
    array[9].next = NULL;

    printf("%i", array[10].array[2]);

    struct number *current = head;
    while(current != NULL)
    {
        printf("Node %i contains the element and is stored in address %p\n", current->array[0], current);
        current = current->next;
    }
}

最佳答案

这不起作用的原因是 struct number 的初始值设定项。可以找到有关使用 C 初始化程序的更多信息 on the GCC website.

结构初始化器: struct number array[10] = {0, 10, 20, 30, 40, 50, 60, 70, 80, 90};

这是一种有歧义的初始化结构的方法,该结构的计算结果为

struct number array[10];
array[0].array = {0, 10, 20, 30, 40, 50, 60, 70, 80, 90};

头指针:

struct number *head = 0;
...
struct number *current = head;
while(current != NULL)

第一行,struct number *head = 0;,等同于struct number *head = NULL;,你的 while 循环永远不会被执行。您可以在此处使用 head = array;head = &array[0];

尾指针: struct number *tail = 90;

这会在 VS2015 中给出以下警告 -

Warning C4047 'initializing': 'number *' differs in levels of indirection from 'int'

您可以在此处使用 tail = &array[9];

打印错误: printf("%i", array[10].array[2]);

这是访问 array 范围之外的元素。 C 通常使用从 0 开始的索引,因此对于您的定义 struct number array[10],最大元素是 array[9]

关于c - 尝试通过链表读取数组时得到错误的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47563621/

相关文章:

c - 在c中重新填充二维数组

c - 如何在 C 中将结构体添加到结构体数组中?

c++ - 寻找搬迁的起源

C动态数组初始化问题

javascript - 如何用另一个数组的元素过滤一个数组?

c - 指向空数组的指针

c++ - 菜单项是单选样式,而不是MF_CHECKED?

ios - 如何使用enum获取字符串值

arrays - 第一个索引中包含字符串的变体数组 - 用 double 型不匹配覆盖该数组

c++ - 如何从包含浮点值的字符数组中获取第一个元素?