使用 glib-library 的 GArray 替换给定索引的值
Replace value of given index using GArray of glib-library
使用 glib 库的 GArray 我想将位置 x 的值设置为给定值。就像我使用 c-array 和 array[x]=5;
为什么我找不到这样做的功能?这不就是一个数组的意思吗?文档:https://developer.gnome.org/glib/stable/glib-Arrays.html
我可以删除旧值并插入新值。但这有点愚蠢。有没有更好的方法?
更新:
在 Gnome Bugzilla 上,有人向我解释这是通常的方式:
int *element = &g_array_index (array, int, i);
*element = 42;
文档没有说清楚,但是因为 g_array_index
是一个宏,您可以使用它来设置和获取。
g_array_index(foo, int, 0) = 23;
g_array_index(foo, int, 1) = 42;
不幸的是,它既不更新也不检查数组的大小有点违背了 GArray 的要点。您必须使用 g_array_sized_new
或 g_array_set_size
来确保有足够的分配内存。
我找不到相关文档或示例。除了在 description that you can use g_array_index
to "access an element", but that's later contradicted by the g_array_index
docs which says that it only "returns the element". Even better would be to provide g_array_set_val
and have no confusion. Perhaps you can let them know?
中模糊提及之外,还应该记录在案
使用 glib 库的 GArray 我想将位置 x 的值设置为给定值。就像我使用 c-array 和 array[x]=5;
为什么我找不到这样做的功能?这不就是一个数组的意思吗?文档:https://developer.gnome.org/glib/stable/glib-Arrays.html
我可以删除旧值并插入新值。但这有点愚蠢。有没有更好的方法?
更新:
在 Gnome Bugzilla 上,有人向我解释这是通常的方式:
int *element = &g_array_index (array, int, i);
*element = 42;
文档没有说清楚,但是因为 g_array_index
是一个宏,您可以使用它来设置和获取。
g_array_index(foo, int, 0) = 23;
g_array_index(foo, int, 1) = 42;
不幸的是,它既不更新也不检查数组的大小有点违背了 GArray 的要点。您必须使用 g_array_sized_new
或 g_array_set_size
来确保有足够的分配内存。
我找不到相关文档或示例。除了在 description that you can use g_array_index
to "access an element", but that's later contradicted by the g_array_index
docs which says that it only "returns the element". Even better would be to provide g_array_set_val
and have no confusion. Perhaps you can let them know?