Question on how to use memcpy

Hey,
I am working on a project were I need to store a long long data type variable in six indexs of a char array. After playing with memcpy, I think it will work. However I am not understanding why if the src variable is not a pointer or array I get an error. Below are examples:


1
2
3
4
5
//This code works
int holder[2] = {17,9};
void * block = holder;
int test[5];
memcpy(&test[2], (int *)block, sizeof(test));


1
2
3
4
5
//This code doesn't works
//This is the way I had thought about for my code
int temp = 990;
unsigned short holder[5];
memcpy(&holder[2], (unsigned short  *)temp, 4);


1
2
3
4
//This code works
int holder[1] = {1794875678};
unsigned short des[5];
memcpy(&des[1], (unsigned short  *)holder, 4));


At this point, I would like a little more info on memcpy. I don't fully understand why my 2nd example want work.Any input on this will be greatly appreicated.

Thanks In Advance
Last edited on
second snippet: temp is an int, NOT a pointer to int! memcpy trying to dereference "990" and causing segfault. Use
1
2
3
4
5
//This code doesn't works
//This is the way I had thought about for my code
int temp = 990;
unsigned short holder[5];
memcpy(&holder[2], (unsigned short  *)(&temp), 4);
closed account (S6k9GNh0)
Notice that you may also use std::fill std::copy to accomplish the same thing, perhaps more optimized (in very rare cases mind you).

Also, memcpy takes void pointers. Rather, your compiler should be giving you warnings about the need of an explicit cast to void* and const void*.
Last edited on
Thanks for feedback. Looks like I will go with the third snippet.
Topic archived. No new replies allowed.