将命令行参数复制到数组中

对于一个程序,我想使用malloc()通过命令行发送的参数的数组副本。

因此,例如,如果我执行./a.out一两三,我想要一个带有{a.out,one,two,3}的数组。

但是,我有一些问题让我的程序工作。 这就是我所拥有的:

static char** duplicateArgv(int argc, char **argv) { char *array; int j = 0; // First allocate overall array with each element of char* array = malloc(sizeof(char*) * argc); int i; // For each element allocate the amount of space for the number of chars in each argument for(i = 1; i < (argc + 1); i++){ array[i] = malloc(strlen(*(argv + i)) * sizeof(char)); int j; // Cycle through all the chars and copy them in one by one for(j = 0; j < strlen(*(argv + i)); j++){ array[i][j] = *(argv + i)[j]; } } return array; } 

正如您可能想象的那样,这不起作用。 我提前道歉,如果这完全没有意义,因为我刚开始学习指针。 此外,我不太确定如何编写代码以在我执行复制所需的操作后释放*数组中的每个元素。

任何人都可以给我一些关于我应该调查什么的建议,让它做我想做的事情吗?

谢谢你的帮助!

您没有分配或复制终止NULL字符:

对于NULL,需要将此行更改为此行。

 array[i] = malloc((strlen(*(argv + i)) + 1) * sizeof(char)); 

循环应该改为:

 for(j = 0; j <= strlen(*(argv + i)); j++){ 

此外,如果您保存strlen()调用的结果,则可以更好地优化代码,因为您在很多地方调用它。

尝试循环如下:

 // For each element allocate the amount of space for the number of chars in each argument for(i = 0; i < argc; i++){ int length = strlen(argv[i]); array[i] = malloc((length + 1) * sizeof(char)); int j; // Cycle through all the chars and copy them in one by one for(j = 0; j <= length; j++){ array[i][j] = argv[i][j]; } } 

首先你需要分配一个char *的向量,而不仅仅是一个char *

 char **array; array = malloc(sizeof(char*)*(argc+1)); // plus one extra which will mark the end of the array 

现在你有一个char*指针的array[0..argc]

然后,对于每个参数,您需要为字符串分配空间

 int index; for (index = 0; index < argc; ++index) { arrray[index] = malloc( strlen(*argv)+1 ); // add one for the \0 strcpy(array[index], *argv); ++argv; } array[index] = NULL; /* end of array so later you can do while (array[i++]!=NULL) {...} */ 

 char *array; 

你定义一个char*类型的对象。 那就是:一个对象,其值可以指向char (以及下一个char ,……,…)

你需要

 char **array; 

使用这种新类型, array的值指向char* ,即另一个指针。 您可以分配内存并将该分配的内存的地址保存在char* ,而不是使用char