user3388399
user3388399

Reputation: 13

How can values of char** argv be copied to another char **

How can I clone char** argv to char** copy?

Upvotes: 1

Views: 1536

Answers (3)

alk
alk

Reputation: 70971

As argv is a NULL-terminated pointer-array there is not need to use argc at all.

#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;
  }

Use it like this:

int main(int argc, char ** argv)
{
   char ** copy = NULL;

   if (-1 == copy_argv(&copy, argv))
   {
     perror("copy_argv() failed");
   }
   else
   {
     /* Use copy here. */
   }
}

Upvotes: 0

Tom Fenech
Tom Fenech

Reputation: 74685

Here's how I would do it:

  1. Allocate an array of char*s the length of argc.
  2. Use strlen to determine the length of each element of argv and allocate enough memory for each one. Remember to add 1 to the length returned by strlen, as this leaves space for the null byte at the end of each of the string.
  3. Use strcpy to copy each value in.
  4. Don't forget to free the memory you have allocated.

#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;
}

Upvotes: 0

Jabberwocky
Jabberwocky

Reputation: 50831

With argc being the number of elements in argv:

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

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

Freeing the allocated memory once we are done with the clone, is left as an exercise to the reader.

Upvotes: 1

Related Questions