【发布时间】:2016-04-23 05:26:57
【问题描述】:
我正在研究这个创建 shell 的小程序。 parse() 接受一个字符指针line 和一个字符指针数组argv,将每个字的地址保存在argv 中。
void parse(char *line, char **argv) {
while (*line != '\0') { /* if not the end of line ....... */
while (*line == ' ' || *line == '\t' || *line == '\n')
*line++ = '\0'; /* replace white spaces with 0 */
*argv++ = line; /* save the argument position */
printf("%p\n",*argv);
while (*line != '\0' && *line != ' ' &&
*line != '\t' && *line != '\n')
line++; /* skip the argument until ... */
}
*argv = '\0'; /* mark the end of argument list */
}
我不明白的是,argv 在函数退出后以某种方式回到了第一个单词。主要函数调用:
parse(line, argv); /* parse the line */
if (strcmp(argv[0], "exit") == 0) /* is it an "exit"? */
exit(0);
argv[0] 在line 的开头,而之前在line 的结尾呢?
【问题讨论】:
-
*argv = '\0';,argv是指向字符串的指针不是字符串,你的意思是*argv = NULL吗? -
这个问题与stackoverflow.com/q/25769443/694576 相关,如果不是与后者重复的话。
-
@AlterMann 可能,尽管 OP 代码确实有效,因为
'\0'与0相同(即int的值为零) -
@M.M,是的,
NULL和 0 在这种情况下是可以互换的。
标签: c arrays pointers parameter-passing