1

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

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

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

4

1 回答 1

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);
}
于 2015-02-19T23:01:33.457 回答