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