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;
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”.
What would I need to do to get a value of 1010?
A few problems with your code as it stands:
int. Sinceintis 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.memcpyworks 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). Usingmemcpyon integers may or may not do what you expect. It’s best to use byte arrays when learning howmemcpyand friends work.memcpyusespB+1as 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 tomemcpywill corrupt random memory, which can crash your program or cause unpredictable results.