Search code examples
cpointerslinked-listvoid

void* in linkedList


i have a simple linked list that looks like this

typedef struct Node { 
    void *data;
    struct Node *next
} Node;

typedef struct Node {
Node *head;
Node *tail;
int size;
} LinkedList

And my add_node function looks like this :

void add_nth_node(LinkedList *list, int n, void *new_data) {
Node *prev, *curr;
Node *new_node;

if (list == NULL) {
    return;
}

/* n >= list->size inseamna adaugarea unui nou nod la finalul listei. */
if (n > list->size) {
    n = list->size;
} else if (n < 0) {
    return;
}

curr = list->head;
prev = NULL;
while (n > 0) {
    prev = curr;
    curr = curr->next;
    --n;
}

new_node = malloc(sizeof(Node));
if (new_node == NULL) {
    perror("Not enough memory to add element!");
    exit(-1);
}

new_node->data = new_data;
new_node->next = curr;
if (prev == NULL) {
    /* Adica n == 0. */
    list->head = new_node;
} else {
    prev->next = new_node;
}

if (new_node->next == NULL) {
    list->tail = new_node;
}

list->size++;

There is something weird when i try to add nodes to the list. When i add them like this :

int i;    
for (i = 0; i < 10; i++) {
     add_nth_node(list, i, &i);
}

But when i add elements like this :

int i, v[10];
    for(i = 0; i < 10; i++) {
        v[i] = i;
        add_nth_node(list_1, i, &v[i]);
    }

Everything is working as expected. Why is that ? Why do i have to put elements is a vector first to add them to the list.


Solution

  • add_nth_node(list, i, &i) // (1)
    // and
    add_nth_node(list_1, i, &v[i]); // (2)
    

    They are not the same but the value of data that you assign for each node is the same in two options.

    (1) You make the pointer point to address of i.

    (2) You make the pointer point to address of v[i].

    Use (1) is very bad idea because, in this case all data of all nodes point to the same address. So if the data of one node changes, the data of all nodes change the value.