如何解决为什么索引 Garray 时缺少一个字符?
我运行了这段为 GUI 程序编写的代码,但出现了一个奇怪的错误,其中一个字符总是按顺序丢失。此代码已简化。
#include <gtk/gtk.h>
int main()
{
GArray *array = g_array_new(FALSE,FALSE,1000); /* I create the array */
int i; /* An iterator used in the for loop. */
char *question = "What does hypersomatic mean?";
/* The insertion loop. */
for (i = 0; i < 10; i++)
{
/* I pass the array along,the data,and the number of elements to insert. */
array = g_array_append_vals(array,question,1);
}
/* The reading loop */
for (i = 0; i < 10; i++)
{
/* I pass along the array,the element type (gchar is correct,I think),and the index of the element. */
char *what_is_this = &g_array_index(array,gchar,i);
printf("%s\n",what_is_this);
}
return 0;
}
我编译了这个:gcc `pkg-config gtk+-3.0 --libs --cflags` main.c
。
这是输出:
超体是什么意思?
hypersomatic 是什么意思?
hypersomatic 是什么意思?
hypersomatic 是什么意思?
hypersomatic 是什么意思?
oes hypersomatic 是什么意思?
es hypersomatic 是什么意思?
s hypersomatic 是什么意思?
超体指的是?
这是什么意思?
解决方法
您正在创建一个 GArray
,每个元素的长度为 1000 个字节,但是当您阅读它时,您告诉 g_array_index()
每个元素的长度为 sizeof(gchar)
个字节(即 1 个字节长)。因此,g_array_index()
返回指向数组数据块中第一次出现字符串的字节 0..10 的指针。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。