Say i have:
unsigned char *varA, *varB, *varC;
varA=malloc(64);
varB=malloc(32);
varC=malloc(32);
How can i put the first 32 byte of varA into varB and the last 32 byte of varA into varC?
memcpy(varB, varA, 32);
memcpy(varC, varA + 32, 32);
It's this simple because the underlying data type is unsigned char, which is the same size as a byte. If varA, varB, and varC were integers, you would need to multiply the size parameter to memcpy (i.e. 32) by sizeof(int) to compute the right number of bytes to copy. If I were being pedantic, i could have multiplied 32 by sizeof(unsigned char) in the example above, but it is not necessary because sizeof(unsigned char) == 1.
Note that I don't need to multiply the 32 in varA + 32 by anything because the compiler does that for me when adding constant offsets to pointers.
One more thing: if you want to be fast, it might be sufficient to just work on each half of varA separately, rather than allocate two new buffers and copy into them.
You could use loop to copy individual bytes one by one:
for (int i = 0; i != 32; ++i)
varB[i] = varA[i];
for (int i = 0; i != 32; ++i)
varC[i] = varA[32 + i];
Or memcpy function from the C runtime library:
memcpy(varB, varA, 32);
memcpy(varC, varA + 32, 32);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With