我正在学习如何在C中获取参数,但是,当我使用以下输入运行下面的代码时,第一个变为null。C字符串变为空
输入:./a.out a b c d e f g h i j k
输出:(null) b c d e f g h i j k
#include <stdio.h>
int main(int argc, char *argv[])
{
int i = 2, j = 0;
char *foo = argv[1];
char *bar[10];
while(j < 10 && i < argc)
{
bar[j++] = argv[i++];
}
bar[j] = NULL;
printf("%s ", foo);
for(j = 0; bar[j] != NULL; j++)
{
printf("%s ", bar[j]);
}
printf("\n");
return 0;
}
有问题吗?当j == 10时,你赋值给b [10],但b只有10的大小,所以你正在分配超出b的范围。 – 2012-01-11 21:54:04
请注意,传递带有“%s”格式空指针的行为是未定义的。你的实现恰好足够友好来打印'“(null)”;其他人不一定会那样做。 – 2012-01-11 21:58:27
在我的设置(Visual Studio 2010)中,它工作。但@WilliamPursell是对的,foo的地址可能只是在酒吧之后,所以bar [10]指向foo。 – holgac 2012-01-11 21:59:29