我必须编写一个从数组中读取int数的程序,然后如果它们大于限制数,则逐个插入它们。我写的是:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
struct number_list{
int high_number;
struct number_list *next;
};
typedef struct number_list number_list;
void insert_in_list(int *array, int lim);
int main(void){
int number_seq[SIZE]={1, 2, 3, 4, 5, 6, 7, 8, 9};
int limit;
scanf("%d\n", limit);
insert_in_list(number_seq, limit);
}
void insert_in_list(int *array, int lim){
int i;
number_list *start_node;
for(i=0; i<SIZE; i++){
if(array[i]>lim){
start_node=malloc(sizeof(number_list));
start_node->high_number=array[i];
printf("%d\n", start_node->high_number);
start_node->next=start_node;
}
}
}
该程序没有任何编译错误(%d
期望*int
类型的参数而不是int
的警告除外,我也没有明白了,所以如果有人能帮助我,那也非常友好)但是在运行时,插入限制号后,会显示分段错误(创建核心转储)。
我认为问题出在insert_in_list函数中,但我不明白它是什么。
答案 0 :(得分:1)
这里有一些问题出现了:
(a)insert_in_list函数需要一个附加参数,告诉要插入哪个列表。
(b)为什么要将number_list结构的成员命名为“high_number”。它不应该只包含 a 号码,因此简称为“数字”吗?
(c)您始终将 next 指针设置为结构本身。如果要形成列表,则应指向下一个节点。
(d)在main中你需要定义一个指向列表第一个节点的指针,只要列表为空,它就应该包含null。这个“锚”代表了你的名单。
(e)作为提示:将指向该锚点的指针传递给insert函数,因为一旦insert函数创建了第一个节点,它就必须将第一个节点的地址存入锚点。因此,您的插入函数应如下所示:
void insert_in_list (number_list** pAnchor, int number)
(f)将输入数组的大小定义为SIZE并在insert_in_list函数中使用该符号并不是一个好主意。相反,要么将数组路径和它的长度作为函数的两个参数,要么 - 正如我在上面的代码行中所做的那样 - 每次调用只传递一个数字到insert函数,并为你要插入的每个数字调用它。
答案 1 :(得分:1)
这将解决您的问题,但我不明白为什么inset_in_list不返回任何内容而您并未使用主函数中的列表 如果那不是强项要么让它返回指向列表的指针或在main中创建列表并将列表的指针传递给函数insert_in_list
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
typedef struct node *node_pointer;
typedef struct node{
int high_number;
node_pointer next;
}number_list;
void insert_in_list(int *array, int lim);
int main(void){
int number_seq[SIZE]={1, 2, 3, 4, 5, 6, 7, 8, 9};
int limit;
scanf("%d", &limit);
insert_in_list(number_seq, limit);
}
void insert_in_list(int *array, int lim){
extern void print_list(node_pointer list);
int i;
node_pointer list = NULL;
for(i=0; i<10; i++){
if(array[i]>lim){
node_pointer newnode, last = list;
newnode = (node_pointer)malloc(sizeof(number_list));
newnode->high_number = array[i];
newnode->next = NULL;
if (last == NULL){
list = newnode;
}//first node
else{
while (1) {
if (last->next == NULL) {
last->next = newnode;
break;
}
last = last->next;
}
}
}
}
print_list(list);
}
void print_list(node_pointer list) {
node_pointer which;
which = list;
printf("\nList 4 :");
if (which == NULL){ printf("Empty\n"); }
while (which != NULL) {
printf("%d", which->high_number);
which = which->next;
}
}