我想使用一个子函数来复制一个字符数组。是这样的:
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
}
这样,我就可以从主函数中调用它,并按这种方式执行操作:
char *MySource = "abcd";
char *MyDestination;
NSV_String_Copy (MySource, MyDestination);
但是,它没有按预期工作。请帮忙!
最佳答案
C 按值传递参数,这意味着您不能使用问题中的函数原型(prototype)更改调用者的 MyDestination
。以下是更新调用方的 MyDestination
副本的两种方法。
选项 a) 传递 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);
}
选项 b) 从函数返回 Destination
,并将其分配给 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);
}
关于c - 子函数内的 malloc、free 和 memmove,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28618434/