问题
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!
回答1:
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);
}
来源:https://stackoverflow.com/questions/28618434/malloc-free-and-memmove-inside-a-subfunction