【发布时间】:2021-01-14 20:49:40
【问题描述】:
我是该网站的新手。我使用代码块。我正在使用 C 语言中的列表,我必须创建一个具有多个函数的程序,但它有一个头文件来声明它们和另一个 .c 文件来实现它们,然后调用 main.c 中的所有内容。当我编译代码时出现问题,插入 n 然后在进入 for 循环后立即按 enter 会出错。我相信'->'运算符有问题。你能帮帮我吗?
//main.c
#include <stdio.h>
#include <stdlib.h>
#include <list.h>
int main()
{
struct element *list;
list = create_list();
return 0;
}
//list.h
#ifndef LIST_H_INCLUDED
#define LIST_H_INCLUDED
#endif // LIST_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct element {
int number;
struct element *pointer;
};
struct element *create_list();
//list.c
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <list.h>
int n = 0;
struct element *create_list() {
struct element *p, *ptr;
int i;
printf("Insert the number of element of the list... ");
scanf("%d", &n);
if (n==0) {
p = NULL;
} else {
p = (struct element*)malloc(sizeof(struct element));
p->number = 0;
for(i=1; i<=n; i++) {
//printf("ciao\n");
ptr->pointer = (struct element *)malloc(sizeof(struct element));
ptr = ptr->pointer;
ptr->number = i;
}
ptr->pointer = NULL;
}
return(p);
}
【问题讨论】:
-
只是一般性评论:您应该将代码放在标头保护之间,而不是在它们之后。
-
@Cb95 你在这个语句中使用了未初始化的指针 ptr ptr->pointer = (struct element *)malloc(sizeof(struct element));
-
包含保护应该保护整个文件,而不仅仅是前几行。你应该检查
malloc的返回值。 -
@VladfromMoscow 这不是初始化吗?结构元素*p,*ptr;感谢回复
-
@Cb95 自动存储时长的变量声明,该变量应显式初始化。否则它们的值是不确定的。
标签: c list initialization structure singly-linked-list