2015-11-18 116 views
1

我学习链表中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)

请问,有人可以解释为什么吗?

谢谢。

+0

而错误是? – kaylum

+0

将'head = head-> link'更改为'head = head-> next'。另外请注意,在'main'中,如果'dequeue'返回一个'NULL','printf'将会出错。 –

+0

什么是错误? – immibis

回答

1
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 
    } 

} 
+0

这是正确的。感谢您的支持。 –

+0

不客气 – milevyo

+0

感谢您的解释。 –

相关问题