C語言 main()函數
C語言main函數的完全格式是
int main(int argc, char* argv[], char* envp[]){
}
int main(int argc, char **argv, char **envp){
}
argc: 是執行程序時命令行參數個數,需要注意,程序本身的名字也算是一個
argv[]: 是命令行中參數的具體參數值
envp[]: 是環境變量, 沒有一個整數來為它技術,是通過最后一個envp[i]==NULL來表示結尾的。
argc和argv 都是比較熟的 不必贅述。
單獨說一下 envp:
例子程序
#include <stdio.h>
int main(int argc, char **argv, char **envp) {
printf(" argc == %d\n", argc);
for(int i=0; i<argc; i++) {
printf(" %s\n", argv[i]);
}
for(int i=0; envp[i]!=NULL;i++) {
printf(" %s\n", envp[i]);
}
return 0;
}
查看 msdn的解釋:
MSDN上的解釋是這樣的:
Microsoft Specific
wmain( int argc, wchar_t *argv[ ], wchar_t *envp[ ] )
envp:
The envp array, which is a common extension in many UNIX? systems【#1】, is used in Microsoft C++. It is an array of strings representing the variables set in the user's environment. This array is terminated by a NULL entry【#2】. It can be declared as an array of pointers to char (char *envp[ ]) or as a pointer to pointers to char (char **envp). If your program uses wmain instead of main, use thewchar_t data type instead ofchar【#3】. The environment block passed to main and wmain is a "frozen" copy of the current environment【#4】. If you subsequently change the environment via a call to putenv or _wputenv, the current environment (as returned by getenv/_wgetenv and the _environ/ _wenviron variable) will change, but the block pointed to by envp will not change. See Customizing Command Line Processing for information on suppressing environment processing. This argument is ANSI compatible in C, but not in C++【#5】.
envp保存了系統環境變量, 以NULL結束,所以可以使用 envp[i]來判斷是否打印完畢
許多unix操作系統普遍擴展了對envp的支持
保存了一個用戶環境變量的字符串,以NULL結束
envp可是是char[]類型 也可以使char*類型,
envp一旦傳入,它就是單純的字符串,不會隨著程序動態設置發生變化,可以使用putenv函數修改變量,也可是用getenv函數查看變量,但是envp本身不會發生變化
-
對ANSI版本兼容,對C++不兼容
可能的應用場景
- 為程序提供參考,可以方便的傳入當前系統運行的環境變量
- 如果程序在運行過程中修改了環境變量, 可以使用此參數進行環境變量的恢復。
補充
通過進一步的查詢
main函數的envp參數不是在POSIX中規定的,而是作為一個擴展來指定的
envp參數提供了一個與envrion相同的功能,盡管此功能在UNIX系統上得到廣泛實施,但應避免使用此功能,因為除了范圍限制外,SUSv3中未詳細說明。