5

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

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
jan1
  • 613
  • 2
  • 10
  • 17

3 Answers3

8

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.

Ed S.
  • 122,712
  • 22
  • 185
  • 265
3

Are you after something like this?

memcpy(data + sizeof(int), &secondInteger, sizeof(int));
Stuart Golodetz
  • 20,238
  • 4
  • 51
  • 80
0

If you don't mind an array and want to do it in one call, I suggest you to copy both the integers into an int array and then write to file.

Ashish Kumar Shah
  • 512
  • 1
  • 9
  • 26
  • If you didn't notice the memory that was returned via `bring_the_8_bytes` (the `data` pointer) is written to and then committed via a call to `send_the_8_bytes_back()`, so allocating new memory wouldn't work. – Ed S. Apr 12 '12 at 16:13