Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use memcpy to copy data from two integers to an array of characters?

Tags:

c++

memcpy

I have a file that can store up to 8 bytes of data.

I have a system(let's call is Sys1) which can bring me 8 bytes from the file and save it in a buffer inside the ram.

I can use these 8 bytes and copy some stuff in it, and then use this system to say "OK I'm done with it, just send these data back to the file".

I want to bring the 8 bytes to the buffer, copy an integer to it, which takes 4 bytes, and on the remaining 4 bytes copy another integer. I just want two integers in 8 bytes, which I believe can be done.

I have managed to copy 4 bytes only, which is just 1 integer and managed to send it back to the file. So I have something like this:

     char *data;
     sys1.bring_the_8_bytes(&data);
    //now the 8 bytes are in the buffer,
    // data points to the first byte of the 8 byte  sequence
    int firstInteger = 10;
    int secondInteger = 20;
    //the two integers 
    memcpy(data,&firstInteger,sizeof(int));
    //now the values of the first integer have been copied successfully.
    sys1.send_the_8_bytes_back();

now this works fine! However I'm not sure how to copy the first integer and then the second immediately.

I should actually know the address of the first byte that is exactly after the last byte that is taken by the first integer, and then use this address as a destination address in the memcpy call, is my thinking correct? if yes,

how can I achieve this?? How can I find out this address that I want?

thanks in advance

like image 588
jan1 Avatar asked Apr 11 '12 21:04

jan1


People also ask

Does memcpy work with arrays?

Memcpy copies data bytes by byte from the source array to the destination array. This copying of data is threadsafe.

What is memcpy used for in C++?

The memcpy() function in C++ copies specified bytes of data from the source to the destination. It is defined in the cstring header file.

What can I use instead of memcpy?

memmove() is similar to memcpy() as it also copies data from a source to destination.


2 Answers

The address you are having problems calculating is simply sizeof(int) bytes past the data pointer you already have. You can just cast the char* to an int* and work with that seeing as you know you always have a valid 8-byte region to write to.

char *data;
sys1.bring_the_8_bytes(&data);
int *tmp = (int*)data;
tmp[0] = 10;
tmp[1] = 20;

Or you can just add to the char* (add sizeof(int)) and do a second memcpy.

like image 69
Ed S. Avatar answered Oct 06 '22 00:10

Ed S.


Are you after something like this?

memcpy(data + sizeof(int), &secondInteger, sizeof(int));
like image 36
Stuart Golodetz Avatar answered Oct 05 '22 22:10

Stuart Golodetz