你可能想了解下命令行參數處理當你給出的程序參數一些列表,例如,
myprog friday tuesday sunday
C語言提供的參數給main()函數其中提供了參數的數量(在這種情況下爲4)以及一個char *(指針)數組。
請注意,sizeof argv是在編譯時計算出來的,其值是系統上指針的大小(4或8)。
首先,我們解釋一下參數的主要功能,
int main(
int argc, //an integer count of the number of arguments provided to the program
char* argv[] //an array of pointers to character arguments
)
你的主要功能被定義到(顯然)打印出來的論點開始在最右邊的參數和工作回到零個參數,
{
int argv_sizeof = argc; //you cannot use sizeof argv the way you specified
//argv_sizeof = 4 in your example, but argv[4] is not valid
//argv_sizeof has a value that is one past the rightmost element of argv[]
while(argv_sizeof) //use argv_sizeof > 0 here; argv_sizeof is 4,3,2,1,0
//when argv_sizeof reaches 0, the while loop terminates
{
printf("%s",argv[--argv_sizeof]); //here you pre-decrement argv_sizeof (3,2,1,0)
//then use argv_sizeof to index into argv[]
//then you print the string at argv[3], argv[2], argv[1], argv[0]
}
//argv_sizeof = 0 here
return 0; //you return the value 0 from the main function
}
'--sizeof argv'是非法的。所以你的程序不能從命令行運行,因爲它甚至不能編譯。 – Paul92
輸出應該是類似於「錯誤:無法應用' - '到右值」。 –
即使它編譯完成,它也會在你運行時陷入一個無限循環,並且當你走出argv的界限時會崩潰。 'while(sizeof argv)'不會終止。 – indiv