Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store an int in a char * that is assigned by malloc

Tags:

c

I was trying to store an int value (all 4 bytes) into a char *:

So, I would like to store the full value i.e all the bytes (all 4) of the int variable into the char such that I use up 4 bytes out of the 512 bytes. I should also be able to read back the value that I assigned. I tried to use a lot of the stuff but couldn't figure this out.

This is for my LFS (Log File System) where I try to store files into data blocks on my disk using fragmentation of data

char *c = malloc(512);
int value = 4096;
like image 244
RI98 Avatar asked Dec 09 '25 09:12

RI98


2 Answers

You can copy into the buffer pointed to by c:

memcpy(c, &value, sizeof(value));

If you want to write another value following that, you can add offset to c:

memcpy(c + sizeof(value), &value2, sizeof(value2));  // adds value2 at an offset right after value

To read the value, you can copy it into a different variable:

int readVal;
memcpy(&readVal, c, sizeof(readVal));
like image 60
Kon Avatar answered Dec 11 '25 10:12

Kon


It's been a while since I've written C or C++, but I believe you can use memcpy to do what you desire.

memcpy(c, &value, 4);

This should copy 4 bytes from the address of value into the bytes you allocated from c. If you wanted to be sure about the size of the integer, you could use sizeof(int) instead of 4. So that would be

memcpy(c, &value, sizeof(int));
like image 28
Luke Avatar answered Dec 11 '25 10:12

Luke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!