I have the following linked list code with a prepend add method:
#include <stdio.h>
#include <stdlib.h>
struct foo {
char a;
int b;
struct foo *next;
};
struct foo * prepend(struct foo * old_head, char c, int d) {
if (!old_head) {
struct foo * head = (struct foo *)malloc(sizeof(struct foo));
head->a = c;
head->b = d;
head->next = NULL;
return head;
} else {
struct foo * temp_node = old_head;
struct foo * head = (struct foo *)malloc(sizeof(struct foo));
head->a = c;
head->b = d;
head->next = old_head;
return head;
}
}
void print_list(struct foo * node) {
if (!node) {
return;
} else if (node->next) {
print_list(node->next);
}
printf("node->a = %s, node->b = %d\n", node->a, node->b);
}
int main() {
struct foo * head = NULL;
head = prepend(head, 'a', 2);
print_list(head);
return 0;
}
that gives me a segfault when I run it. I know the segfault is triggered by the line print_list(head);
but I'm not really sure why. I only need to store a single char in a so I don't want to use a pointer if I don't have to but I think I might have to. I'm very new to C and any help would be appreciated.
You are printing node->a
, a char
, using ac string format specifier "%s"
so printf()
is interpreting your char value as a pointer and things go badly quickly. The char should be printed as "%c"
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.