c - 在C中将字符串拆分为数组时遇到问题

标签 c arrays string split 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
  ******* 
  ******* 

谢谢

最佳答案

strtok 文档指定:

This end of the token is automatically replaced by a null-character, and the beginning of the token is returned by the function.

每个标记都是 7 位数字,并且您为每个标记分配 7 个字符。但是,这并没有考虑空字符终止符。您实际上需要 8 个字符的空间。

您应该将 temp_dow 声明更改为:

char temp_dow[3][8];

关于c - 在C中将字符串拆分为数组时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27325714/

相关文章:

c - 如何编写单个函数以按行和按列排序的二维数组进行搜索(限制是函数应该类似于 int search(int *A,int n,int key))

c++ - 如何为 Linux 编写自己的自定义启动画面?

字符数组按字母顺序排序-C

ios - JS 对象到 Swift 结构

mysql - 如何使用 concat 压缩多行

c - 为什么我不能在不定义额外变量的情况下使用这个 C 程序?

javascript - 第一次单击时函数无法正确触发

python - 在 Python 中的字符串末尾添加一个整数

python - str.replace 与 Pandas str.replace 中的字符串替换

arrays - 在 node.js 和 socket.io 中发送数组时出现错误