2014-03-06 50 views

回答

1

随着argc是argv中元素的个数:

char** copy = (char**)malloc(argc * sizeof(char*)) ; 

    for (int i = 0; i < argc ; i++) 
    { 
    copy[i] = strdup(argv[i]) ; 
    } 

释放分配的内存一旦我们与克隆完成后,作为练习留给读者。

0

这是我会怎么做:

  1. 分配char* S的argc长度的数组。
  2. 使用strlen来确定每个元素的长度argv并为每个元素分配足够的内存。请记得在strlen返回的长度上加1,因为这会在每个字符串的末尾留出空字节空间。
  3. 使用strcpy每个值复制。
  4. 不要忘了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; 
} 
0

作为argvNULL封端的指针阵列有不需要使用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(&copy, argv)) 
    { 
    perror("copy_argv() failed"); 
    } 
    else 
    { 
    /* Use copy here. */ 
    } 
}