简体   繁体   English

链接列表中的 void*

[英]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:我的 add_node function 看起来像这样:

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.为什么我必须先放置元素是一个向量才能将它们添加到列表中。

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 . (1) 您使指针指向i的地址。

(2) You make the pointer point to address of v[i] . (2) 您使指针指向v[i]的地址。

Use (1) is very bad idea because, in this case all data of all nodes point to the same address.使用 (1) 是一个非常糟糕的主意,因为在这种情况下,所有节点的所有data都指向同一个地址。 So if the data of one node changes, the data of all nodes change the value.所以如果一个节点的data发生变化,所有节点的数据都会改变值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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