0

I am getting from a function a pointer to the (empty at the start) data of a block.

This pointer is:

char* data;

And my job is to insert different types of data in this block. I know only the data type (string/int/float) and their length in bytes.

For example, for an inserting integer, I want to give to each block a form like:

|block_num|age|weight|favorite_number|

So my main question is, how can I insert the number to the block and get them like? I would like smth like data[3] to get weight each time.

I have tried to use memset and memcpy, but there was no success.

Thanks for your time!

Nick Stavr
  • 13
  • 4

1 Answers1

-1

In case you want to write to an address pointed to by a char* you need to cast it to proper type (that you want) and de-reference it.

For example: (here returnedFromFunc is similar to your data).

char *returnedFromFunc = func();

you can write an int by properly casting it to int*

*((int*)(returnedFromFunc))=intValue;

To go to the next location you would simply do this:-

char *originalPtrValue = returnedfromFunc; // store it for future referece
returnedfromFunc += sizeof intVar;

Similarly you can access it also if you know the type of data you are storing.

For example if it is int

you can do this

printf("%d ", *((int*)(returnedFromFunc)));

Using the sizeof operator you can access different locations.(offseting from the initial char* value).

You need to know how much memory is there where you can write. Otherwise there is a chance that you might try to write into memory that you have no permission to.(out of the bound )

user2736738
  • 30,591
  • 5
  • 42
  • 56