user3857354
user3857354

Reputation:

How to copy an array of char pointer to another in C

I am trying to store an array of char pointer to another array of char pointer. I am getting segmentation fault for the same.

int main(int argc, const char* argv[])
{   
    int argcCpy = argc;
    char* argvCpy[10] = {};

    for(argcCpy = argc; argcCpy>0; argcCpy--)
    {   
        argvCpy[argcCpy] = (char *) malloc(strlen(argv[argcCpy]));
        memcpy(argvCpy[argcCpy], argv[argcCpy], strlen(argv[argcCpy]));
        printf("\nCount: %d, string: %s", argcCpy, argvCpy[argcCpy]);
    }
    return 0;
}

I spent more than enough time to make this work but I am not able to do it. Also, the same kind of question is already asked which is also left unanswered. If anybody can let me know the working code for the same, it would be really so helpful.

Hoping this to be answered.

Link of the similar question left out unawnsered -- C Beginner - Copying a char *array to another char *array

Thanks.

Upvotes: 0

Views: 2387

Answers (2)

jdarthenay
jdarthenay

Reputation: 3147

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, const char* argv[])
{
    int argcCpy = argc;
    char* argvCpy[10] = {};

    if (argc > 9)
    {
        return 1;
    }

    for(int i = argc; i > 0; i--)
    {
        if (argv[i] == NULL)
        {
            argvCpy[i] = NULL;
        }
        else
        {
            argvCpy[i] = (char *) malloc(strlen(argv[i]) + 1);
            if (argvCpy[i] != NULL)
            {
                strcpy(argvCpy[i], argv[i]);
            }
        }
    }

    for (int i = 0; i <= argcCpy; i++)
    {
        if (argvCpy[i] != NULL)
        {
            printf("Count: %d, string: %s\n", i, argvCpy[i]);
        }
        else
        {
            printf("Count: %d, string is null\n", i);
        }
    }

    return 0;
}

Check argc is not too high. argv[argc] is NULL, take this into account. Use strcpy, and allocate enough room for the ending \0.

Edit: Second for loop to show content.

Upvotes: 1

Jabberwocky
Jabberwocky

Reputation: 50778

You must allocate one byte more for the terminating NUL:

Change

 malloc(strlen(argv[argcCpy]);

to

 malloc(strlen(argv[argcCpy] + 1);

and you also must copy one byte more with memcpy

Change

 memcpy(argvCpy[argcCpy], argv[argcCpy], strlen(argv[argcCpy]));

to

 memcpy(argvCpy[argcCpy], argv[argcCpy], strlen(argv[argcCpy]) + 1);

BTW you can replace

 memcpy(argvCpy[argcCpy], argv[argcCpy], strlen(argv[argcCpy]) + 1);

by

 strcpy(argvCpy[argcCpy], argv[argcCpy]);

which is simpler and more clear.

And last but not least replace

for(argcCpy = argc; argcCpy>0; argcCpy--)

by

for(argcCpy = argc - 1; argcCpy>0; argcCpy--)

The last element of the argv array is argv[argc-1].

But be aware that you'll run into problems if you have more then 10 command line arguments.

Upvotes: 1

Related Questions