C struct 的属性在预期为引用时为 null

C struct's attribute is null when expected to be a reference

typedef struct node {
    char *string;
    struct node* next;  
} node;

typedef struct {
    node *head;  
    node *tail;
    node *curr;
} list;

list llInit(){
    list *linkedList = malloc(sizeof(list));
    linkedList->head = NULL;
    linkedList->tail = NULL;
    linkedList->curr = NULL;

    return *linkedList;
}

int llSize(list *myList){
    if (myList->head == NULL){
        return 0;
    }

    int size = 1;
    node *instance = myList->head;

    while(instance->next != NULL){
        instance = instance->next;
        size++;
    }

    return size;
}

int llAddToFront(list *myList,char *toStore){
    if (toStore == NULL){
        return 0;
    }

    node *newNode = malloc(sizeof(struct node));
    newNode->string = toStore;

    newNode->next = myList->head;
    myList->head = newNode;

    if (myList->tail == NULL){
        myList->tail = newNode;
    }

    return 1;
}

int llAddToBack(list *myList, char *toStore){
    if (toStore == NULL){
        return 0;
    }

    if (myList->head == NULL){
        return llAddToFront(myList, toStore);
    }

    node *newNode = malloc(sizeof(struct node));
    newNode->string = toStore;

    newNode->next = myList->tail;
    myList->tail = newNode;

    return 1;
}

int main() {
    // add one element to front, size should be 1
    list two = llInit();
    llAddToFront(&two, "one");
    if (llSize(&two) != 1){
        printf("Test 2: Fail - size should be %d, was %d.\n", 1, llSize(&two));
    }

    if (one.head == NULL){
        printf("ERROR!!!!");
    }

    if (one.tail.string != "one"){
        printf("Test 2: Fail - unexpected tail string.\n");
    }
}

这是一个 C 语言的链表,用于存储字符串。

出于某种原因,(主要)我的头是空的并打印错误消息。我相信我在 llAddToFront 中正确设置了它。此外,之后的 if 块会产生分段错误,我不明白为什么。

你不能这样做:
if (one.tail.string != "one")

你应该这样做:
if (strcmp(one.tail.string, "one"))

希望对您有所帮助

这个可以编译吗?名为 one 的列表未声明,您正在测试其头部是否为空。 我认为你是 运行 一个旧的二进制文件。