标题有点令人困惑,但很难描述.
在我们的c方法中:
char* wc(char** cmds, char** stringstoread, char** filename, char* result)
{
char arr[4];
int count = 0;
while(*(cmds) != NULL)
{
if(strcmp(*(cmds), "-l") == 0) // Check each commands
arr[count++] = 'l';
else if(strcmp(*(cmds), "-c") == 0)
arr[count++] = 'c';
else if(strcmp(*(cmds), "-m") == 0)
arr[count++] = 'm';
else if(strcmp(*(cmds), "-w") == 0)
arr[count++] = 'w';
cmds++;
}
if(count == 0)
{
arr[0] = 'l', arr[1] = 'c', arr[2] = 'm',arr[3] = 'w';
}
while((*stringstoread) != NULL)
{
printf("inputs are %s \n", *(stringstoread));
stringstoread++;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
我们处于调试模式atm,但截至目前,我们无法弄清楚为什么最后一个while循环打印出来:
inputs are input 1
inputs are input 2
inputs are -l
inputs are -w
inputs are -c
inputs are -m
Run Code Online (Sandbox Code Playgroud)
当这样调用方法时,我们不知道-l,-w -c和-m是如何进入stringstoread的:
char tresult[10000];
char *tcmds[] = { "-l", "-w", "-c", "-m"};
char *tinput[] = {"input 1 \n\n", "input 2 \n\n"} ;
char *tfilename[] = {"fil 1", "fil 2"} ;
char *tmp = wc(tcmds, tinput, tfilename, tresult);
Run Code Online (Sandbox Code Playgroud)
这有点乱,但希望有人可以提供帮助,我们是C的新手,所以认为我们遇到了对语言的标准误解.
您需要null终止数组.像这样:
char *tcmds[] = { "-l", "-w", "-c", "-m", NULL};
char *tinput[] = {"input 1 \n\n", "input 2 \n\n", NULL} ;
char *tfilename[] = {"fil 1", "fil 2", NULL} ;
Run Code Online (Sandbox Code Playgroud)
原因是您在循环遍历这些数组,直到遇到空值.但是,由于程序中定义的数组不以空值结尾,因此您可以循环结束它们.
当你的循环结束时,你现在有了未定义的行为,任何事情都可能发生.实际发生的是,编译器将相邻的数组布置在一起,然后从一端到另一端运行.
我没有检查你的代码中的任何其他内容.毫无疑问会有更多的错误,但我认为这是对这个问题的主要解释.