简体   繁体   中英

this code gives head->next = NULL although it should not

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

// linked-list implementation of stack

typedef struct stack node;

struct stack{

    int value;
    node* next;    

};

void push(node*,int);
void pop(node*);



int main(){

node* head=malloc(sizeof(node));
head->next = NULL;
push(head,5);
if (head->next == NULL){
printf("head->next is NULL.");
}
pop(head);

}


void push(node* head,int value){

    head->value = value;
    node* temp = malloc(sizeof(node));
    temp->next = head;
    head = temp;

}

The above code prints head->next = NULL although it should not because when push is called then temp->next = head and then head = temp so now the head->next should be equal to the previous head's location.

in see that in your push() function you want to change the head of the list but actually you are passing it by-value so it will not be affected.

node *head means that you have a pointer to a NODE and that you can actually modify only the properties of that NODE , not the head pointer itself.

you should use node **head which is a pointer to a pointer so it means that with it you can actually modify the head pointer.

在此处输入图片说明 在此处输入图片说明

That was a very short explanation... please try to read more about Pass-By-Value in C and Pass-By-Reference .

After this modification you must also pass the address of the head pointer as a parameter (&head) and make changes to it as *head ( in your function)

Here is the code:

void push(node**,int); void pop(node*);

int main(){

node* head=malloc(sizeof(node));
head->next = NULL;
push(&head,5);
if (head->next == NULL){
printf("head->next is NULL.");
}
//pop(head);

}


void push(node** head,int value){

    (*head)->value = value;
    node* temp = malloc(sizeof(node));
    temp->next = *head;
    (*head) = temp;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM