2014-12-05 60 views
0

我想将字符串拆分为数组temp_dow。麻烦将字符串拆分为C中的数组

//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 
    ******* 
    ******* 

感谢

+1

'7' - >'8':+1为NULL字符。 – BLUEPIXY 2014-12-05 22:32:13

+2

'strcpy(temp,tok1); strcpy(temp_dow [i],temp);' - **为什么?? **另外,为NUL终止符分配空间。 – 2014-12-05 22:32:38

+0

确实。为什么不简单地'strcpy(temp_dow [i],tok1);'?删除上面的两行。 – 2014-12-05 22:32:44

回答

0

的strtok的文件规定:

令牌的这一端以空字符自动替换,并且令牌的开头部分是由函数返回。

您的每个令牌都是7位数字,并且您为每个令牌分配7个字符。但是,这不包含空字符终止符。你实际需要8个字符的空间。

您应该将temp_dow声明更改为:

char temp_dow[3][8];