问题描述
我想用一个子功能来复制一个字符数组。它是这样的:
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!
推荐答案
C会按值参数,这意味着你不能改变调用者的 mydestination中
使用功能原型的问题。这里有两种方法来更新的调用者的副本 mydestination中
。
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
.
选项A)传递的地址 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);
}
选项B)返回目标
从功能,并将其分配给 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);
}
这篇关于malloc的,免费的,memmove与一个子功能内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!