1

I want to use a subfunction to copy a char array. it is like this:

void NSV_String_Copy (char *Source, char *Destination)
{
    int len = strlen(Source);
    if (*Destination != NULL)
        free(Destination);
    Destination = malloc(len + 1);
    memmove(*Destination, Source, len);
    Destination[len] = '\0';             //null terminate
}

that way, I can call it from the main function and perform the operation this way:

char *MySource = "abcd";
char *MyDestination;

NSV_String_Copy (MySource, MyDestination);

However, it does not work as intended. please help!

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
CaTx
  • 1,421
  • 4
  • 21
  • 42

1 Answers1

2

C passes arguments by value, which means that you can't change the caller's MyDestination using the function prototype in the question. Here are two ways to update the caller's copy of MyDestination.

Option a) pass the address of MyDestination

void NSV_String_Copy (char *Source, char **Destination)
{
    int len = strlen(Source);
    if (*Destination != NULL)
        free(*Destination);
    *Destination = malloc(len + 1);
    memmove(*Destination, Source, len);
    (*Destination)[len] = '\0';             //null terminate
}

int main( void )
{
    char *MySource = "abcd";
    char *MyDestination = NULL;

    NSV_String_Copy(MySource, &MyDestination);
    printf("%s\n", MyDestination);
}

Option b) return Destination from the function, and assign it to MyDestination

char *NSV_String_Copy (char *Source, char *Destination)
{
    if (Destination != NULL)
        free(Destination);

    int len = strlen(Source);
    Destination = malloc(len + 1);
    memmove(Destination, Source, len);
    Destination[len] = '\0';             //null terminate

    return Destination;
}

int main( void )
{
    char *MySource = "abcd";
    char *MyDestination = NULL;

    MyDestination = NSV_String_Copy(MySource, MyDestination);
    printf("%s\n", MyDestination);
}
user3386109
  • 34,287
  • 7
  • 49
  • 68
  • thank you, sir. you fixed my problem. first time I have to deal with pointer to pointer. mucho appreciado. – CaTx Feb 20 '15 at 14:19