Adding an integer to a char array in c

It might be a stupid question, but I still don't get it. I have a char char arr [100] array with some data

 char arry[100] ---- some data;
 int test;
 memcpy(&test,array+4,sizeof(int))

What will this memcpy do thanks to SKP

+4
source share
5 answers

This can be useful for so-called data serialization.

Say if someone saved an integer to a file.

Then you read the file into the buffer ( arryin your case) as a stream of bytes. Now you want to convert these bytes to real data, for example. in your case, an integer testthat was stored at offset 4.

. - memcpy , .

, :

 memcpy(&test,array+4,sizeof(int))

... sizeof (int) , 4- array , test ( int). test , arry, , :

 memcpy(array+4, &original_int, sizeof(int))

. , :

  • .;
  • ;
+3

array[4] test. 32- sizeof(int)= 4. memcpy 4 &test, 4 .

+2

, , 4 ( - int ) 4- 7- arry test.

+2

C void * memcpy (void * str1, const void * str2, size_t n) n str2 strong > str1, :

str1 - , , -casted void *

str2 - , -casted void *

n - ,

memcpy , str1

, [4], sizeof (int) ( 4 , 32- ),

+1

memcpy():

void * memcpy ( void * destination, const void * source, size_t num );

num , source, , destination.

:

  • num= sizeof(int)
  • destination= &test
  • source= &array[4] char array

, sizeof(int)==4 array[4], array[5], array[6] array[7] test

, :

endianless: array[4] .

, array[7]=0x80 array4]=array[5]=array[6]=0x00, test 00000080 test -2 ^ 31.

if array[7]=0x2Aand array[5]=array[6]=array[4]=0x00, then it testwill contain 2A000000 and testwill cost 42 (i.e. 0x0000002A).

Here is the test code that should be compiled 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;
}
0
source

All Articles