日期:2014-05-16  浏览次数:20570 次

写了段代码,发现个问题,求解释
//test.c

#include <stdio.h>
#include <string.h>

static void command(const char *command, char *cmd[])
{
static char buff[30];
int i=0;
strcpy(buff, command); 
cmd[i] = strtok(buff, " ");
while (cmd[i] != NULL)
{
i++;
cmd[i] = strtok(NULL, " ");
}
}

int main(int argc,char *argv[])
{
if (argc <= 1)
{
return 0;
}
int index = atoi(argv[1]);
char m[] = "this test cmd";
char *p[3];
printf("%d %d\n", index, atoi(argv[1]);
command(m, p);
printf("%d %d\n", index, atoi(argv[1]));
return 0;
}

这段代码是把输入的字符串按空格的方式分别存放,但是诡异的是index的值改变了,我没有对index进行操作。
gcc test.c -o test
./test 5
5 5
0 5
想不通,求解释啊~~~~~

------解决方案--------------------
command函数中有问题,问题语句;cmd[i] = strtok(NULL, " ");,应该改成:cmd[i] = strtok(buff+strlen(cmd[i-1], " "));因为你每次的查找都应该基于上次的查找位置
------解决方案--------------------
我测试打印结果如下:
hacps:~/root/test> ./aaa 5 6
5 5
5 5

但是在
static void command(const char *command, char *cmd[])
{
static char buff[30];
int i=0;
strcpy(buff, command);
cmd[i] = strtok(buff, " ");
while (cmd[i] != NULL)
{
i++;
cmd[i] = strtok(NULL, " ");
}}

数组越界了。