【发布时间】:2021-02-18 07:50:42
【问题描述】:
我正在尝试在 C 上做一个练习。有两个数组,count 和 list。 count 是一个初始填充为 0 的整数数组,而 list 是一个队列数组。我的代码应该采用由空格分隔的数字对,例如。 “1 2”。对于每一对数字,我必须将count数组中的2nd number-1位置加1,然后在list数组的1st number-1位置的队列头部放入一个包含第二个数字的节点.我的代码在下面,在收到第一对数字后会导致分段错误。删除第 24-30 行会删除错误,但我不明白是什么导致了这个错误。谁能指出它为什么会出现分段错误?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node Node;
struct node {
int succ;
Node *next;
};
void set_initial_array(int count[], int n, Node *list[]);
void handle_input(char string[], int count[], Node *list[]);
void set_initial_array(int count[], int n, Node *list[]) {
for (int i = 0; i < n; i++) {
count[i] = 0;
list[i] = NULL;
}
}
void handle_input(char string[], int count[], Node *list[]) {
int j = atoi(&string[0]), k = atoi(&string[2]);
count[k - 1]++;
if (list[j - 1] != NULL) { // Removing line 24-30 removes error
Node head = {k, list[j - 1]};
list[j - 1] = &head;
} else {
Node head = {k, NULL};
list[j - 1] = &head;
}
}
int main() {
char string[4];
int count[15];
Node *list[15];
set_initial_array(count, n, list); //fill count with 0 and list with NULL
while (fgets(string, 4, stdin) != NULL && strcmp(string, "0 0") != 0) {
handle_input(string, count, list);
}
}
【问题讨论】:
-
这怎么编译,
main中没有变量n? -
非静态局部变量在从声明它们的函数返回时将失效,并将指向它们的指针存储到在 returnig 后仍然存在的变量不是一个好主意。
标签: c linked-list segmentation-fault