I really appreciate your feedback, but I am still confused (I am a completely C++ beginner and pointers are driving me crazy, please be patient). I should have described my issue exactly since the beginning.
I have a portion of memory allocated with "malloc" (the use of malloc is a requirement). In this portion I must define the following:
* 8 bytes for an integer.
* 4 bytes for an integer.
* 4 bytes for an integer.
* n bytes for data.
This structure repeats several times in the portion of memory allocated with "malloc".
Initially, the memory block is of type *void:
1 2
|
void *MemPtr;
MemPtr = malloc(1024);
|
To set a value (500 for example) for the first 8-byte integer, maybe I can cast MemPtr to (long long) as follows:
|
*((long long*)MemPtr) = 500;
|
How can I set the value for the second and third 4-byte integers? I guess my question translates to, how can I calculate the address of the second and third 4-byte blocks? or how do I add n-bytes to an address to calculate the next address?
I should "skip" the last "n bytes" of data and start again with the next block of one 8-byte integer, one 4-byte integer and one 4-byte integer, skip the "n bytes" of data and start with the next block, and so on.
Something that I found is that if I cast "MemPtr" to "*bool" and add 1, then I advance byte by byte. It works but, is it valid?
1 2 3 4 5 6 7 8 9
|
void *MemPtr;
MemPtr = malloc(256);
for (int i = 0; i < 256; i++)
{
cout << i << " - Address of MemPtr: " << (((bool*)MemPtr) + i) << endl;
}
free(MemPtr);
|
Regards.