3

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?

2
  • Your question has remarkable little to do with pointers and you might want to rethink what it means to "split them". Commented Jan 30, 2013 at 22:37
  • 2
    I would recommend a union... just to clarify, i'm suspecting it's gonna be bits instead of bytes in the end. Commented Jan 30, 2013 at 22:37

3 Answers 3

11
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.

Sign up to request clarification or add additional context in comments.

2 Comments

First of all thanks a lot for your answer, you have been very clear and exhaustive :) Then how can i work with "half of varA"? Let's say i need to do void *function(int, half_of_varA);, how can i pass only "half of memory"?
You would choose one of void* p = function(1234, varA); or void* p = function(1234, varA + 32); depending on which half of varA you need to use. And I am using 1234 as a guess as to the first parameter of function(), of course.
1

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); 

3 Comments

Loops certainly work, but I would trust the compiler and/or memcpy implementer in this case. They can do tricks in the underlying assembly that a compiled loop can't touch (at least without a great optimizer), like moving multiple bytes at once.
It's just a different approaches. Copying through the loop could include some processing, like bit shuffling for example.
Yes, if processing is required, a loop is necessary.
-4

Ok let's do this....

uint64 source; uint32 upperBytes, lowerBytes; upperBytes = source&0xFFFFFFFF00000000; lowerBytes = source&0x00000000FFFFFFFF; 

Homework done.

1 Comment

I don't understand your answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.