【发布时间】:2021-01-02 16:35:54
【问题描述】:
我是相当 c 新手,我正在实施 DHT。 为此,我必须将节点 ID 存储在列表中。
节点 ID 为
我可以很好地设置节点的 ID,我还使用mpz_out_str 验证它。当我用g_slist_foreach 遍历它并打印 ID 时,它会输出一个巨大的数字,这完全不相关。
我怀疑这与从 gpointer 到 Node 的 cast 有关,或者我可能存储不正确(非常新指针)
代码:
#include <glib.h>
#include <gmp.h>
#include <stdio.h>
typedef struct {
mpz_t *node_id;
} Node;
void print_iterator(gpointer item, gpointer prefix) {
// Also, since the item is of type gpointer,
// It has to be casted back to Node.
Node *node = (Node *)item;
// outputs a HUGE, completely random number.
mpz_out_str(stdout, 10, node->node_id);
printf("\n");
};
GSList *add_node(GSList *nodes) {
Node *node = malloc(sizeof(Node));
mpz_t id;
mpz_init(id);
char *f = "123";
mpz_set_str(id, f, 10);
node->node_id = &id;
// prints correct value
mpz_out_str(stdout, 10, node->node_id);
nodes = g_slist_append(nodes, node);
return nodes;
}
int main(int argc, char const *argv[]) {
GSList *nodes = NULL;
nodes = add_node(nodes);
g_slist_foreach(nodes, print_iterator, "‑‑>");
return 0;
}
相关链接:
https://developer.gnome.org/glib/stable/glib-Singly-Linked-Lists.html
https://gmplib.org/manual/
【问题讨论】:
-
不要同时使用 C 和 C++ 标签。如果您使用的是 C++ 编译器,您应该会收到一条错误消息,告诉您您使用了错误的指针类型。