本文介绍了了解memcpy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
int a = 10;
int* pA = &a;
long long b = 200;
long long* pB = &b;
memcpy (pB,pA,4);
memcpy (pB+1,pA,4);
cout<<"I'm a memcpy!: "<<*(pB)<<endl;
我正在用memcpy做一些测试,以自学记忆的工作原理.我正在尝试将b =设置为"1010".我可以将值从a复制到b,但是然后我尝试将内存偏移1个字节,然后再写入10个字节,但它不起作用,它只会输出"10".
I'm doing some tests with memcpy to teach myself how memory works. What I am trying to do is make b = to "1010". I can copy the value from a to b, but then I try to offset the memory by 1 byte and write another 10 but it doesn't work it only outputs "10".
我需要怎么做才能得到1010的值?
What would I need to do to get a value of 1010?
推荐答案
您的代码所存在的一些问题:
A few problems with your code as it stands:
- 您复制了4个字节,但目的地是类型
int
.由于不能保证int
为任何特定大小,因此在执行这种memcpy
之前,需要确保其长度至少为4个字节. -
memcpy
在字节级别工作,但是整数是一系列字节.根据您的目标体系结构,整数内的字节可能会以不同的方式排列(大端,小端等).在整数上使用memcpy
可能会或可能不会达到您期望的效果.学习memcpy
和朋友的工作方式时,最好使用字节数组. - 您的第二个
memcpy
使用pB+1
作为目标.这不会将指针前移一个字节,而是将其前移sizeof(*pB)
个字节.在这种情况下,这将使其指向无效地址(过去是变量的末尾).对此memcpy
的调用将破坏随机存储器,这可能会使您的程序崩溃或导致不可预测的结果.
- You copy 4 bytes, but the destination is type
int
. Sinceint
is not guaranteed to be any particular size, you need to make sure that it is at least 4 bytes long before you do that sort ofmemcpy
. memcpy
works on the byte level, but integers are a series of bytes. Depending on your target architecture, the bytes within an integer may be arranged differently (big-endian, little-endian, etc). Usingmemcpy
on integers may or may not do what you expect. It's best to use byte arrays when learning howmemcpy
and friends work.- Your second
memcpy
usespB+1
as the target. This doesn't advance the pointer one byte, it advances it bysizeof(*pB)
bytes. In this case, that leaves it pointing to an invalid address (past the end of the variable). This call tomemcpy
will corrupt random memory, which can crash your program or cause unpredictable results.
这篇关于了解memcpy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!