【发布时间】:2014-12-05 22:28:49
【问题描述】:
我想将一个 char 字符串拆分成一个数组 temp_dow。
//parse incoming string
char input[] = {"1111111,0000000,1010101"};
char temp_dow[3][7];
char *tok1;
int i = 0;
tok1 = strtok(input, ",");
while (tok1 != NULL) {
char temp[7];
strcpy(temp, tok1);
strcpy(temp_dow[i],temp);
tok1 = strtok(NULL, ",");
printf ("<<<<<<<< %s\n",temp_dow[i]);
i++;
}
printf ("******* %s\n",temp_dow[0]);
printf ("******* %s\n",temp_dow[1]);
printf ("******* %s\n",temp_dow[2]);
输出不匹配。 while 循环外的 temp_dow[] 是完全错误的。它显示的是指针的值而不是实际值?
这是输出。
<<<<<<<< 1111111
<<<<<<<< 0000000
<<<<<<<< 1010101
******* 1010101
*******
*******
谢谢
【问题讨论】:
-
7-->8: +1 表示 NUL 字符。 -
strcpy(temp, tok1); strcpy(temp_dow[i],temp);- 为什么?? 另外,为 NUL 终止符分配空间。 -
确实如此。为什么不简单地
strcpy(temp_dow[i], tok1);?删除上面的两行。 -
啊,谢谢! Nul 终止符是问题所在。
-
在较新的程序中使用
strsep()。虽然strtok()是可移植的,但它无法处理空字段。
标签: c arrays string split char