如何将char** argv
克隆到char** copy
?
char** argv
char** copy
答案 0 :(得分:1)
argc
是argv中的元素数量:
char** copy = (char**)malloc(argc * sizeof(char*)) ;
for (int i = 0; i < argc ; i++)
{
copy[i] = strdup(argv[i]) ;
}
完成克隆后,释放已分配的内存,留给读者练习。
答案 1 :(得分:0)
我将如何做到这一点:
char*
长度argc
的数组。 strlen
确定argv
的每个元素的长度,并为每个元素分配足够的内存。请记住在strlen
返回的长度上加1,因为这会在每个字符串的末尾为空字节留出空间。 strcpy
复制。free
已分配的记忆。#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char ** argv)
{
char ** copy = malloc(argc * sizeof (char*));
int i;
size_t sz;
for (i = 0; i < argc; ++i) {
sz = strlen(argv[i]) + 1;
copy[i] = malloc(sz * sizeof (char));
strcpy(copy[i], argv[i]);
}
for (i = 0; i < argc; ++i) {
printf("%s\n", copy[i]);
}
for(i = 0; i < argc; ++i) free(copy[i]);
free(copy);
return 0;
}
答案 2 :(得分:0)
由于argv
是一个NULL
终止的指针数组,所以根本不需要使用argc
。
#define _GNU_SOURCE /* for strdup() */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int copy_argv(char *** pcopy, char ** argv)
{
int result = 0;
char ** copy = argv;
{
while (*copy)
{
++copy;
}
copy = (*pcopy) = malloc((copy - argv + 1) * sizeof (*copy));
}
if (NULL == copy)
{
result = -1;
goto lblExit;
}
while (*argv)
{
*copy = strdup(*argv);
if (NULL == *copy)
{
result = -1;
/* Clean up. */
while (copy > *pcopy)
{
--copy;
free(*copy);
}
free(*pcopy);
*pcopy = NULL;
goto lblExit;
}
++copy;
++argv;
}
*copy = NULL;
lblExit:
return result;
}
像这样使用:
int main(int argc, char ** argv)
{
char ** copy = NULL;
if (-1 == copy_argv(©, argv))
{
perror("copy_argv() failed");
}
else
{
/* Use copy here. */
}
}