gpt4 book ai didi

c - 在出列之前返回链表中的第一个元素时出现问题

转载 作者:太空宇宙 更新时间:2023-11-04 03:34:24 26 4
gpt4 key购买 nike

我正在学习 C 中链表的实现。我的以下实现有问题:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

typedef struct msg * Message;
struct msg{
int SN;
Message next;
};

Message dequeue(Message *head);
void new_msg(Message *head);

int main(){

Message M, head = NULL;

new_msg(&head);
M= dequeue(&head);
if(M != NULL) printf("Message %d has been deleted:", M->SN);

}


Message dequeue(Message *head)
{

Message m, temp;

if(*head == NULL){
return NULL;
}
else
{
temp = *head;
m = temp; // To return the message before removing it from the queue
head = head->next; // ERROR IS HERE
free(temp);
}

return (m);
}

void new_msg(Message *head){

Message m, last;
m = malloc(sizeof(struct msg));

last = *head;
srand(0);
m->SN = rand();

if (*head == NULL)
{
*head = m;
}
else
{
while (last->next != NULL)
{
last = last->next;
}
last->next = m;
}


}

我将扩展我的程序以充当一个队列,它需要在完全出队之前返回队列中的第一个节点(即头),但我不断收到此错误:

/bin/sh -c 'make -j 8 -e -f  Makefile'
----------Building project:[ hello - Debug ]----------
gcc -c "/Users/CFC/Library/Application Support/codelite/test/hello/main.c" -g -O0 -Wall -o ./Debug/main.c.o -I. -I.
/Users/CFC/Library/Application Support/codelite/test/hello/main.c:38:20: error: member reference base type 'Message' (aka 'struct msg *') is not a structure or union
head = head->next;
~~~~^ ~~~~
1 error generated.
make[1]: *** [Debug/main.c.o] Error 1
make: *** [All] Error 2
====1 errors, 0 warnings====

head = head->next; 这行 Message dequeue(Message *head) 中。

请问有人能解释一下原因吗?

谢谢。

最佳答案

Message dequeue(Message *head)
{

Message temp=NULL;

if(*head )
{
temp = *head;

*head = temp->next; // ERROR HERE
// ^____________________ you have to dereference the pointer head
//free(temp); // do not free it
}

return temp;
}



int main()
{
Message M, head = NULL;

new_msg(&head);
M= dequeue(&head);
if(M) // check if not NULL
{
printf("Message %d has been deleted:", M->SN);
free(M); // now its time to free it
}

}

关于c - 在出列之前返回链表中的第一个元素时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33771531/

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