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

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Oh what the heck +1 :) I like your answer better than mine.
tmp[0] = 10; tmp[1] = 20; might be a clearer way to write the last two lines.
This is undefined behavior, it's a strict alias violation.
@FrançoisAndrieux: You are correct, I should probably fix this
3

Are you after something like this?

memcpy(data + sizeof(int), &secondInteger, sizeof(int));

Comments

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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.