malloc,free和memmove在一个子功能中

时间:2015-02-19 22:40:21

标签: c malloc free memmove

我想使用子函数来复制char数组。它是这样的:

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);

但是,它不能按预期工作。请帮忙!

1 个答案:

答案 0 :(得分:2)

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);
}

选项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);
}