According to the documentation of [`memcpy()`](
[To see links please register here]
) :
> void * memcpy ( void * destination, const void * source, size_t num );
Copies the values of `num` bytes from the location pointed by `source` directly to the memory block pointed by `destination`.
In your case :
- `num`=`sizeof(int)`
- `destination`=`&test` A pointer to test
- `source`=`&array[4]` A pointer to the fourth element of the array of char `array`
Hence, if `sizeof(int)==4` it will copy `array[4]`, `array[5]`,`array[6]` and `array[7]` to `test`
There are questions that can help you understand the memory layout of integers :
-
[To see links please register here]
-
[To see links please register here]
There is also an issue with endianless : on my computer, `array[4]` corresponds to the least significant byte.
Consequently, if `array[7]=0x80` and `array4]=array[5]=array[6]=0x00` then `test` will contain 00000080 and `test` will worth -2^31.
if `array[7]=0x2A` and `array[5]=array[6]=array[4]=0x00` then `test` will contain 2A000000 and `test` will worth 42 (that is 0x0000002A).
Here is a test code to be compiled by `gcc main.c -o main`
#include <stdio.h>
#include <string.h>
int main(int argc,char *argv[]){
char array[100];
int test;
printf("sizeof(int) is %ld\n",sizeof(int));
array[4]=0x00;
array[5]=0;
array[6]=0;
array[7]=0x80;
memcpy(&test,&array[4],sizeof(int));
printf("test worth %d or(hexa) %x\n",test,test);
array[4]=0x2A;
array[5]=0;
array[6]=0;
array[7]=0x00;
memcpy(&test,&array[4],sizeof(int));
printf("test worth %d or(hexa) %x\n",test,test);
return 0;
}