Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding an integer to a char array in c

Tags:

c

It may be silly question but still am not getting it. I do have a char array say char arr[100] having some data

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

What does this memcpy will do Thanks SKP

like image 211
user3160866 Avatar asked Apr 09 '15 16:04

user3160866


3 Answers

This might be useful in so-called serialization of data.

Say, if someone saved an integer into a file.

Then you read the file into a buffer (arry in your case) as a stream of bytes. Now you want to convert these bytes into real data, e.g. in your case integer test which has been stored with offset 4.

There are several ways to do that. One is to use memcpy to copy bytes into area where compiler would treat them as an integer.

So to answer your question:

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

...will copy sizeof(int) number of bytes, starting from 4-rth byte from array into memory allocated for variable test (which has type int). Now test has the integer value which was saved into arry originally, probably using the following code:

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

Doing this requires some knowledge of hardware and the language. As there are many complications, among which:

  • byte order in integers.;
  • data alignment;
like image 181
fukanchik Avatar answered Oct 19 '22 23:10

fukanchik


It just copy the element array[4] to variable test. On 32-bit machine sizeof(int) = 4. memcpy will copy 4 bytes to the address &test which can hold 4 bytes.

like image 30
haccks Avatar answered Oct 19 '22 22:10

haccks


This will copy probably 4 bytes (depending on your machine and compiler--your int might be bigger or smaller) from the 4th through 7th bytes of arry into the integer test.

like image 27
Lee Daniel Crocker Avatar answered Oct 20 '22 00:10

Lee Daniel Crocker