gpt4 book ai didi

c - 将命令行参数读入 c 中的新数组?

转载 作者:太空宇宙 更新时间:2023-11-04 07:34:29 24 4
gpt4 key购买 nike

没有办法知道有多少参数;用户可以提供不确定长度的列表。

我对 C 语言很烂。如何从命令行数组中读取参数并将其读取到新的字符串数组中?

老实说,我什至不知道如何制作一个单独的字符串数组。一个例子会非常有帮助。

最佳答案

是的。

如果您查看 main 函数的完整原型(prototype):

int main(int argc, char **argv, char **env)

argc:这是参数计数器,它包含用户给出的参数数量(假设命令是cd,输入cd home 将给出 argc = 2 因为命令名称始终是参数 0)

argv:这是参数值,它是一个大小为 argcchar* 数组,指向参数本身。

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).

给变量加星号称为取消引用。如果您不知道这是如何工作的,我强烈建议您看一看。

我希望这个解释足够好。如果您仍有问题,请发表评论,我会编辑此答案。

关于c - 将命令行参数读入 c 中的新数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10212223/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com