malloc、free和memmove在子函数中
我想使用一个子函数来复制字符数组。是这样的:malloc、free和memmove在子函数中,c,malloc,free,memmove,C,Malloc,Free,Memmove,我想使用一个子函数来复制字符数组。是这样的: 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); Dest
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
}
这样,我可以从main函数调用它,并通过以下方式执行操作:
char *MySource = "abcd";
char *MyDestination;
NSV_String_Copy (MySource, MyDestination);
但是,它并没有按预期工作。请帮忙 C按值传递参数,这意味着您不能使用问题中的函数原型更改调用方的
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);
}
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);
}
选项b)从函数返回目的地
,并将其分配给我的目的地
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);
}
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);
}
FWIW认为,空白样式非常特殊,因此很难阅读。我已经采取了编辑的自由,使它可读的世界其他地方…而且,“它不工作的意图”不是一个有用的问题描述。我认为你需要指向这里的指针(双星)-至少对于
目的地
。有趣的是,您仅在两个位置使用*目的地
。您没有将MyDestination初始化为NULL。谢谢您,先生。你解决了我的问题。第一次我必须处理指针对指针的问题。非常感激。