[英]Assigning char member of struct in function in c
我有以下链接列表代码和前置添加方法:
#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;
}
当我运行它时会给我一个段错误。 我知道段错误是由行print_list(head);
触发的print_list(head);
但我不确定为什么。 我只需要在a中存储一个字符,这样就不必使用指针,但是我认为可能必须使用指针。 我是C的新手,将不胜感激。
您正在使用ac字符串格式说明符"%s"
来打印node->a
,一个char
,因此printf()
会将char值解释为指针,并且事情进展很快。 字符应打印为"%c"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.