我正在學習如何在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