如何通过索引从GLib GArray中获取元素?
如何通过索引从GLib的GArray中获取结构体元素?
我正在编写一个依赖GLib的应用,使用它的动态数组GArray。查看GLib.Array文档后,了解到可以通过结构体的data属性访问数组数据,但实际操作中无法用常规方括号语法读取数据:
struct TestStruct { bool some_value; int some_other_value; }; int main(int argc, char *argv[]) { GArray* test_array = g_array_new(false, false, sizeof(struct TestStruct)); struct TestStruct test_struct = { .some_value = true, .some_other_value = 4 }; g_array_append_val(test_array, test_struct); struct TestStruct test_struct_2 = { .some_value = false, .some_other_value = 9 }; g_array_append_val(test_array, test_struct_2); printf("%i\n", test_array->data[0].some_other_value); }
编译这段代码时,得到如下错误:
../../../../../../../../../Projects/test/src/main.c:214:45: error: invalid type argument of ‘->’ (have ‘int’) 214 | printf("%i\n", (test_array->data)[0]->some_other_value); | ^~
尝试用点符号替代箭头访问属性也无效,因为在此上下文里test_array->data[0]被视为int类型,无法执行这类访问操作。那该如何通过索引从GArray中获取元素?
解决方法
问题根源在于GArray->data的类型是gpointer(本质是void*),C语言不会自动将其转换为你的结构体指针类型,直接使用data[0]会被当作int处理,这是旧C标准对void*下标访问的默认行为。
你可以通过两种方式正确访问元素:
1. 强制类型转换后使用下标
先把data转换为指向TestStruct的指针,再通过下标访问元素:
struct TestStruct *elem_ptr = (struct TestStruct*) test_array->data; printf("%i\n", elem_ptr[0].some_other_value);
2. 使用GLib官方推荐的g_array_index()宏
GLib专门提供了g_array_index()宏来安全访问GArray元素,无需手动处理类型转换:
printf("%i\n", g_array_index(test_array, struct TestStruct, 0).some_other_value);
该宏的语法为g_array_index(数组指针, 元素类型, 索引),它会自动完成类型转换,能避免手动转换可能引发的错误,是更稳妥的写法。
内容的提问来源于stack exchange,提问作者Newbyte
相关产品推荐
相关产品推荐

