我正在学习如何在 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;
}
最佳答案
在循环结束时,您将 NULL
写入 bar[10]
,但您只分配了 bar[0 - 9]
.这可能会覆盖 foo
。
关于C 字符串变为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8827187/