GSList (GLib) 问题

发布于 2024-11-06 07:36:33 字数 451 浏览 10 评论 0原文

您好,

我正在尝试使用 glib.h 中的 GSList,但在使用 char * 元素填充列表时遇到问题。

这是代码:

GSList * res = NULL;
char * nombre;

while (...) {
 nombre = sqlite3_column_text(resultado, 1);
     res = g_slist_append (res, nombre);
}   

printf("number of elements: %i\n", g_slist_length(res));
printf("last element: %s\n", g_slist_last(res)->data);

当我打印元素数量时,我看到列表不为空。但是当我打印最后一个元素时,它没有显示任何内容......

我做错了什么?

谢谢!

HI,

I'm trying to use GSList from glib.h but I'm having problems when filling the list with char * elements.

Here's the code:

GSList * res = NULL;
char * nombre;

while (...) {
 nombre = sqlite3_column_text(resultado, 1);
     res = g_slist_append (res, nombre);
}   

printf("number of elements: %i\n", g_slist_length(res));
printf("last element: %s\n", g_slist_last(res)->data);

When I print the number of elemnts, I see the list is not empty. But when I print the last element, It doesn't show anything...

What Am I doing wrong?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情定在深秋 2024-11-13 07:36:33

该列表将仅保留指针值。如果指针指向的内存后来被覆盖,就会遇到问题。

解决方案可能是复制存储之前的字符串:

res = g_list_append(res, g_strdup(nombre));

这将存储指向新字符串的指针,这些新字符串存储在新分配的内存中,每个字符串都不同。当然,之后您需要通过在每个存储的指针上调用 g_free() 来清理它,否则您的程序将泄漏内存:

g_list_free_full(res, g_free);

这会调用标准的 g_free() 函数在每个数据指针上,然后释放列出自己。

The list will only retain the pointer value. If the memory the pointer is pointing at is later overwritten, you will have problems.

The solution could be to duplicate the string before storing it:

res = g_list_append(res, g_strdup(nombre));

This will store pointers to new strings, stored in freshly-allocated memory, different for each string. Of course, you need to clean this up afterwards by calling g_free() on each of the stored pointers, or your program will leak memory:

g_list_free_full(res, g_free);

This calls the standard g_free() function on each data pointer, before freeing the list itself.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文