如何将char ** argv的值复制到另一个char **

时间:2014-03-06 17:08:16

标签: c pointers

如何将char** argv克隆到char** copy

  • 原创 - char** argv
  • copyto - char** copy

3 个答案:

答案 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)

我将如何做到这一点:

  1. 分配char*长度argc的数组。
  2. 使用strlen确定argv的每个元素的长度,并为每个元素分配足够的内存。请记住在strlen返回的长度上加1,因为这会在每个字符串的末尾为空字节留出空间。
  3. 使用strcpy复制。
  4. 中的每个值
  5. 不要忘记free已分配的记忆。

  6. #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(&copy, argv))
   {
     perror("copy_argv() failed");
   }
   else
   {
     /* Use copy here. */
   }
}