简体   繁体   English

在C函数中分配struct的char成员

[英]Assigning char member of struct in function in c

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); 我知道段错误是由行print_list(head);触发的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. 我只需要在a中存储一个字符,这样就不必使用指针,但是我认为可能必须使用指针。 I'm very new to C and any help would be appreciated. 我是C的新手,将不胜感激。

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. 您正在使用ac字符串格式说明符"%s"来打印node->a ,一个char ,因此printf()会将char值解释为指针,并且事情进展很快。 The char should be printed as "%c" . 字符应打印为"%c"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM