Mah*_*ran 1 c recursion pointers linked-list singly-linked-list
我在C中编写了一个链表(使用gcc编译器),并试图以递归方式打印它.它告诉"分段错误",并且还仅打印第一个值.任何人都可以提出纠正它的选项..?这是我的代码.
#define MAX 10
#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node *next;
};
void printRecursively(struct node *start) {
if (start != NULL) {
printf("%d\n", start->value);
start = start->next;
printRecursively(start);
}
}
void main() {
struct node *nodes[MAX];
for (int i = 0; i < MAX; i++) {
nodes[i] = malloc(sizeof(struct node));
nodes[i]->value = i + 1;
nodes[i]->next = nodes[i + 1];
}
printRecursively(nodes[0]);
}
Run Code Online (Sandbox Code Playgroud)
您的代码将next
每个新分配的代码的指针初始化为未初始化的值.向后运行循环并确保初始化ast节点的next
指针NULL
.
int main(void) {
struct node *nodes[MAX];
for (int i = MAX; i-- > 0;) {
nodes[i] = malloc(sizeof(struct node));
nodes[i]->value = i + 1;
nodes[i]->next = (i == MAX - 1) ? NULL : nodes[i + 1];
}
printRecursively(nodes[0]);
/* for good style, free the allocated memory */
for (int i = 0; i < MAX; i++) {
free(nodes[i]);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如您所述,有一个简单的解决方案,即增加索引值并检查内存分配失败:
int main(void) {
struct node *nodes[MAX];
for (int i = 0; i < MAX; i++) {
nodes[i] = malloc(sizeof(struct node));
if (nodes[i] == NULL) {
fprintf(stderr, "memory allocation failure\n");
exit(1);
}
nodes[i]->value = i + 1;
nodes[i]->next = NULL;
if (i > 0) {
nodes[i - 1]->next = nodes[i];
}
}
printRecursively(nodes[0]);
/* for good style, free the allocated memory */
for (int i = 0; i < MAX; i++) {
free(nodes[i]);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)