Frage

Ich starte Lernzeiger und verknüpfte Liste in C, aber ich habe ein Problem:

struct pointer
{
       int id;
       struct pointer *next;
};

int pop(struct pointer *head, struct pointer *tail);

main()
{
    struct pointer *head = NULL;
    head = (struct pointer*)malloc(sizeof(struct pointer));
    head->id=1;
    struct pointer *tail = head;
    tail->next=NULL;
    pop(head,tail);
    if (head==NULL) printf ("In main, head is NULL");
    else printf ("In main, head is NOT NULL");
}    

int pop(struct pointer *head, struct pointer *tail)
{
    int toReturn;
    struct pointer *toFree;
    if (head!=NULL)
    {
       toReturn = head->id;
       toFree = head;
       head = head->next;
       free(toFree);
       if (head==NULL)
          tail = head;
    }
    else toReturn = -1;
    if (head==NULL) printf ("In function, head is NULL\n");
    else printf ("In function, head is NOT NULL\n");
    return toReturn;
}

warum ist die Ausgabe:

In function, head is NULL
In main, head is NOT NULL

Ich erwarte das:In Funktion ist head NULL In der Hauptsache ist head NULL

Dies ist meine erste Erfahrung mit Zeigern in C und kann nicht verstehen, was ich falsch mache

War es hilfreich?

Lösung

In Ihrem pop funktion, die sie ändern möchten head variabel.Da C Parameter pro Wert übergibt, müssen Sie die Adresse von angeben head variable, um ihren Wert zu ändern.Das gleiche gilt für tail.

Ändern Sie also Ihre Pop-Funktion von:

int pop(struct pointer *head, struct pointer *tail)

zu:

int pop(struct pointer **head, struct pointer **tail)

Und wenn Sie diese Funktion aufrufen, verwenden Sie pop(&head, &tail);

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top