【发布时间】:2018-01-29 02:29:13
【问题描述】:
我通过以下方式声明一个字符串数组:
char *commands[100];
然后我继续进入一个 while 循环,读取用户输入的命令:
while(getcmd(buf, sizeof(buf), cmd_count) >= 0){
printf(2, "cmd_count: %d\n", cmd_count);
buf[strlen(buf)-1] = 0;
printf(2, "string buf: -%s-\n", buf);
commands[cmd_count] = buf;
printf(2, "commands: %s\n", commands[0]);
printf(2, "commands: %s\n", commands[1]);
printf(2, "commands: %s\n", commands[2]);
printf(2, "commands: %s\n", commands[3]);
cmd_count++;
}
这是两次迭代的输出:
0 EZ$ ls
cmd_count: 0
string buf: -ls-
commands: ls
commands: (null)
commands: (null)
commands: (null)
EZ$ echo hello
cmd_count: 1
string buf: -echo hello-
commands: echo hello
commands: echo hello
commands: (null)
commands: (null)
尽管cmd_count 在第二次迭代中显然是 1,但它重写了第 0 位和第 1 位。什么给了?
【问题讨论】:
-
请编辑您的问题并添加minimal reproducible example。
-
printf(2, "cmd_count: %d\n", cmd_count);应该是printf("cmd_count: %d\n", cmd_count);您的尝试会产生"warning: passing argument 1 of ‘printf’ makes pointer from integer without a cast" -
@DavidC.Rankin 你可能没有在 xv6 环境中测试
-
啊,你可能是对的。谢谢汤姆。现在我知道它是像 CS50 这样古怪的东西之一......