我正在尝试在C上进行练习。有两个数组,count
和list
。 count
是一个整数数组,最初以0填充,而list
是一个队列数组。我的代码应该采用以空格分隔的数字对。 “ 1 2”。对于每对数字,我必须在2nd number-1
数组的count
位置加1,然后在1st number-1
位置的队列开头放置一个包含第二个数字的节点list
数组的值。我的代码在下面,接收到第一对数字后导致分段错误。删除第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);
}
}
答案 0 :(得分:1)
这里有个问题:
Node head = {k, list[j - 1]};
list[j - 1] = &head;
head
是一个局部变量,一旦handle_input
函数返回,它将在作用域内(或简单地说:它将被销毁)。
在这一行list[j - 1] = &head;
中,该局部变量的地址存储在列表数组中,该数组实际上指向main
中提供的数组。
您需要通过分配内存来不同地处理此问题:
Node *head = malloc(sizeof(*head));
head->succ = k;
head->next = list[j - 1]
list[j - 1] = head;
可能还有其他问题,我没有检查。
别忘了在main
中的某个时候释放分配的内存。