gpt4 book ai didi

c - 子函数内的 malloc、free 和 memmove

转载 作者:太空宇宙 更新时间:2023-11-04 02:44:37 25 4
gpt4 key购买 nike

我想使用一个子函数来复制一个字符数组。是这样的:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com