GString的用法

默认分类 · 2013-07-21

呃,初次接触GString,用了总是不尽如人意

一、问题

我初始化一个GString,其值为init,然后在其后加一个值,123,则输出应该为init123,但我得到的是123,不说了,上示例代码和运行结果。

下面是示例代码

 1 #include <glib-2.0/glib.h>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 int main(int argc, char * argv[])
 5 {
 6   int i = 123;
 7   char str[ 10 ];
 8   sprintf(str,"%d",i);
 9   GString * teststring = g_string_new("init");
10   printf ( "the teststring is %s\n",*teststring );
11   g_string_append(teststring,str);
12   printf ( "the teststring is %s\n",*teststring );
13   g_string_free(teststring,TRUE);
14 }

下面是编译过程

gcc testgstring.c -o 1  -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include  -lglib-2.0 

编译的输出为

testgstring.c: In function ‘main’:
testgstring.c:10:3: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘GString’ [-Wformat]
testgstring.c:12:3: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘GString’ [-Wformat]

运行的结果

 $./1
the teststring is init
the teststring is 123

二、解决之道

1、参考资料

https://openhome.cc/Gossip/GTKGossip/GString.html

2、更改后的源程序

#include <glib-2.0/glib.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char * argv[])
{
  int i = 123;
  char str[ 10 ];
  sprintf(str,"%d",i);
  GString * teststring = g_string_new("init");
  printf ( "the teststring is %s\n",teststring->str );
  g_string_append(teststring,str);
  printf ( "the teststring is %s\n",teststring->str );
  g_string_free(teststring,TRUE);
}

3、编译之后的运行结果

 ./1
the teststring is init
the teststring is init123
编程
Theme Jasmine by Kent Liao