如何将char数据复制到内存中已经定义的更小的char?

问题描述 投票:0回答:1

也许这是一个简单的问题,但我找不到解决方案。

功能:

int function(char **data)
{
char data_new[542] = {.......};
memcpy(*data, data_new, sizeof(data_new));
return 1;
}

它不起作用,因为 *data 比 data_new 更小。如何正确增加*data的大小才能成功memcpy()?我不想只是这样做:

*data = data_new;

我想将数据复制到这个指针指向的内存区域。

我尝试过:

*data = (char*)realloc(*data, sizeof(data_new) * 2);

提前致谢。

c windows memory-management
1个回答
0
投票

你重新分配

#include <stdio.h>
#include <stdlib.h>
 
// your original function with (almost) no changes
int function(char **data) {
    char data_new[542] = "bar";
    data_new[541] = 'Z';              // just to illustrate
    *data = realloc(*data, 542);      // realloc, would be better to receive the original size
                                      // and have a way to send back the new size
    memcpy(*data, data_new, sizeof(data_new));
    return 1;
}
 
int main(void) {
    char *foo = malloc(200);
    function(&foo);
    printf("%c%c%c ... %c\n", foo[0], foo[1], foo[2], foo[541]);
    free(foo);
    return 0;
}

参见https://ideone.com/v10p2S

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.