gpt4 book ai didi

当预期为引用时,C 结构体的属性为 null

转载 作者:行者123 更新时间:2023-11-30 20:55:56 24 4
gpt4 key购买 nike

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 block 会产生段错误,我不明白为什么。

最佳答案

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

关于当预期为引用时,C 结构体的属性为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29482405/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com