0

I am trying to remove an element from a linked list using structures in C. The part that makes no sense is that I wrote a function for it and the same body of the function when placed in the main function produces different results.

#include<stdio.h>

struct entry {
    int value;
    struct entry *next;
};

void removeEntry(struct entry *prior) {
    prior = prior -> next;
}

int main(void) {

    struct entry e1;
    e1.value = 1;

    struct entry listPointer;
    listPointer.next = &e1;

    struct entry e2;
    e2.value = 2;

    struct entry e3;
    e3.value = 3;

    e1.next = &e2;
    e2.next = &e3;
    e3.next = (struct entry *) 0;


    removeEntry(listPointer.next);

    printf("%i\n", listPointer.next -> value);

    listPointer.next = listPointer.next -> next;

    printf("%i\n", listPointer.next -> value);

    return 0;
}

Output:

1
2
  • You need to learn about variable scoping. C passes function parameters *by value*. `prior = prior -> next` does not do what you think it does. `prior` is a local variable and changes to it do not affect the caller's version that was passed in. You need to pass in a pointer (`struct entry **`) if you want to change that value. – kaylum Sep 05 '16 at 03:16
  • http://www.geeksforgeeks.org/how-to-write-functions-that-modify-the-head-pointer-of-a-linked-list/ Please go though this one once, this will solve all your queries... – Flying disk Sep 05 '16 at 05:57

0 Answers0