问题描述
我想一个串复制到C字符串数组:
I am trying to copy a "string" to array of strings in C:
const gchar *strAuth, *strEditor, *strTitle;
gchar *strings[18][150];
strcpy(strings[0],strAuth);
在编译时,GCC是给予警告:
警告:传递从兼容的指针类型'的strcpy'的参数1 [默认启用]
while compiling, gcc is giving warning:warning: passing argument 1 of ‘strcpy’ from incompatible pointer type [enabled by default]
可能的话,由于该故障矿,在code的后期
Possibly, due to this fault of mine, the check and print in the later part of the code
g_print("%s", strings[0]);
int i=0;
while (i <= 18) {
if (strlen(strings[i]) != 0) {
g_string_append_printf(tstring, "\t%s=\"%s\",\n",
keyword[i], strings[i]);
i++;
}
}
也没有工作(它是印刷空字符串为好)。
C是不是我的语言,所以好心帮
is also not working (it is printing empty strings as well).C is not my language, so kindly help
注:thecked 并的,但未能帮助自己
注意:gchar对应的标准C char类型。在巧舌如簧
NB:thecked this and this, but failed to help myselfNB: gchar "Corresponds to the standard C char type." in glib
推荐答案
最直接的修复(不建议一个完全不同的方法)需要一对夫妇的修正。
The most immediate fix (without suggesting a totally different approach) requires a couple of fixes.
有关警告的事情是,你正在创建的18x150指针数组,但我猜你要18串长度150,这样的定义应该是:
The thing about the warning is that you are creating an array of 18x150 pointers, but I guess you want 18 strings of length 150, so the definition should be:
gchar strings[18][150]; // 18 strings of 150 chars
您code的样子,你可能还假定为零初始化(空字符串,如果不填写),所以你可以添加:
The way your code looks, you would probably also assume to be zero initialized (empty strings if not filled) so you might add:
gchar strings[18][150]= { "", }; // 18 empty strings of 150 chars
在code另一个(更严重的)错误是你的循环运行[0 ... 18]。但是,你的字符串列表仅 gchar *串[18] [150];
所以它应该运行[0..17]。同时也应该发生的我递增时长字符串[我]是零(否则你将得到一个无限循环,从来没有达到结束,如果一个字符串为空)。
Another (more severe) error in your code is that your loop is running [0...18]. But your list of strings is only gchar *strings[18][150];
so it should run [0..17]. Also the increment of I should also happen when length strings[i] is zero (otherwise you will get an infinite loop, never reaching the end if one string is empty).
while (i < 18) { // <-- FIX
if (strlen(strings[i]) != 0) {
g_string_append_printf(tstring, "\t%s=\"%s\",\n",
keyword[i], strings[i]);
}
i++; // <-- FIX
}
这篇关于字符复制到字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!