简体   繁体   English

为什么在特定情况下需要 memcpy

[英]Why is memcpy needed in particular case

In the following function:在以下 function 中:

void cp (char **x, char ** y) {
    while (*x) {
        * y = malloc(strlen (*x)+1);
        // * y++ = *x++;
        memcpy (*y++, *x++, strlen (*x) + 1);
    }
}

Why do I need to use memcpy ?为什么我需要使用memcpy Why can't I just use * y++ = * x++ .为什么我不能只使用* y++ = * x++ When I try doing it that way, I get a segfault when trying to free that memory.当我尝试这样做时,在尝试释放 memory 时出现段错误。

x and y are char** s. xychar** s。 If you just do * y++ = * x++ , then you're making the intermediate pointers point to the same place, rather than actually copying the data from the first location to the second.如果您只是执行* y++ = * x++ ,那么您正在使中间指针指向同一个位置,而不是实际将数据从第一个位置复制到第二个位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM