问题描述
因此,有我在撞头两晚在一排的一个问题:
So there is a problem I am headbanging over two nights in a row:
(tuple1和tuple2是空指针传递给这个函数)
(tuple1 and tuple2 are void pointers passed to this function)
char *data;
data = (char*) calloc (76, 1);
memcpy(data, tuple1, 32);
memcpy(data+32, tuple2, 44);
我们的想法是分配内存等于 tuple1
和 tuple2
(<$ C的大小之和$ C> tuple1 是32个字节, tuple2
44),然后复制32个字节 tuple1 $ C的$ C>并粘贴在数据的地址,之后复制44个字节
tuple2
和粘贴32字节数据的地址后。
The idea is to allocate memory equal to the sum of the sizes of tuple1
and tuple2
(tuple1
is 32 bytes and tuple2
is 44) and then copy the 32 bytes of tuple1
and paste them at the address of data and after that copy the 44 bytes of tuple2
and paste them 32 bytes after the address of data.
问题是,如果我只复制 tuple1
或只 tuple2
这是真正复制它应该是(我打印资料太长功能放在这里),但是当我做了两个内存拷贝第一个的memcpy()
工作正常,但第二次却没有。
The thing is if I copy only tuple1
or only tuple2
it is really copied where it is supposed to be (I am printing data with way too long function to put here), but when I do the two memory copies the first memcpy()
works fine but the second doesn't.
谁能帮我这个严重的问题?
Can anyone help me with this serious problem?
推荐答案
与更小的东西,哪一个更容易调试开始实验:
Begin your experiment with something smaller, which is easier to debug:
void* tuple1 = calloc(2, 1);
char* content1 = "ab";
memcpy(tuple1, content1, 2);
void* tuple2 = calloc(4, 1);
char* content2 = "cdef";;
memcpy(tuple2, content2, 4);
char *data = data = (char*) calloc (6, 1);
memcpy(data, tuple1, 2);
memcpy(data+2, tuple2, 4);
printf("%.*s\n", 6, data); // should print: abcdef
这篇关于复制内存时的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!