[英]Reading command line arguments into a new array in c?
沒有辦法知道有多少論點; 用戶可以提供不確定長度的列表。
我對C非常不好。如何從命令行數組中讀取參數並將其轉換為新的字符串數組?
坦率地說,如果我要誠實的話,我甚至不知道如何制作一系列單獨的字符串。 一個例子是超級有用的。
就在這里。
如果你看一下main函數的完整原型:
int main(int argc, char **argv, char **env)
argc :這是參數計數器,它包含用戶給出的參數個數(Assumin命令為cd
,輸入cd home
將給出argc = 2,因為命令名總是參數0)
argv :這是參數值,它是一個大小為argc的char*
指向參數本身的數組。
env :這是一個表(作為argv),包含調用程序時的環境(例如,通過shell,使用env
命令給出)。
至於制作一系列事物的例子:兩種方式是可能的:
首先,一個固定長度的數組:
char tab[4]; // declares a variable "tab" which is an array of 4 chars
tab[0] = 'a'; // Sets the first char of tab to be the letter 'a'
第二,可變長度數組:
//You cannot do:
//int x = 4;
//char tab[x];
//Because the compiler cannot create arrays with variable sizes this way
//(If you want more info on this, look for heap and stack memory allocations
//You have to do:
int x = 4; //4 for example
char *tab;
tab = malloc(sizeof(*tab) * x); //or malloc(sizeof(char) * x); but I prefer *tab for
//many reasons, mainly because if you ever change the declaration from "char *tab"
//to "anything *tab", you won't have to peer through your code to change every malloc,
//secondly because you always write something = malloc(sizeof(*something) ...); so you
//have a good habit.
使用數組:
無論你選擇聲明它(固定大小還是可變大小),你總是以相同的方式使用數組:
//Either you refer a specific piece:
tab[x] = y; //with x a number (or a variable containing a value inside your array boundaries; and y a value that can fit inside the type of tab[x] (or a variable of that type)
//Example:
int x = 42;
int tab[4]; // An array of 4 ints
tab[0] = 21; //direct value
tab[1] = x; //from a variable
tab[2] = tab[0]; //read from the array
tab[3] = tab[1] * tab[2]; //calculus...
//OR you can use the fact that array decays to pointers (and if you use a variable-size array, it's already a pointer anyway)
int y = 21;
int *varTab;
varTab = malloc(sizeof(*varTab) * 3); // An array of 3 ints
*varTab = y; //*varTab is equivalent to varTab[0]
varTab[1] = x; //Same as with int tab[4];
*(varTab + 2) = 3; //Equivalent to varTab[2];
//In fact the compiler interprets xxx[yyy] as *(xxx + yyy).
星號變量稱為解除引用。 如果您不知道這是如何工作的,我強烈建議您看看。
我希望這個解釋得足夠好。 如果您仍有疑問請發表評論,我將編輯此答案。
int main ( int argc, char *argv[] ) {
}
這是您聲明主要輸入功能的方式。 argc
是用戶輸入的參數數量INCLUDING程序名稱,它是argv
的第一個字符串( argv[0]
=程序名稱)。
因為argv已經是一個字符串數組,我建議你使用它,因為這就是它的用途。 (只是不要忘記跳過索引0)
int main(int argc, char *argv[])
這就是你的程序中主要應該是什么樣子。 argc
是傳遞給程序的參數數量。 argv
是一個字符串列表,它是傳遞給程序的參數,其中argv [0]是程序名。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.