为什么索引 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 的指针。