Reputation: 1
Let's say we have a char array:
char pool[1000];
and a pointer
char* ptr;
the pointer stores an address to a block of data in Pool. I want to store this address in the pool and retrieve it as well.
Basically, what I want to do is a linked-list that is embedded in the char array Pool. The reason is that i'm not allowed to create any new variables (globally), and I cant include new headers, among other restrictions.
So the question is : how to I segment and fit a 4 byte address in (let's say) the first 4 elements of pool[] , and how do I retrieve it again for the purpose of modification.
This operation will happen frequently so it needs to be fast...and of course not rely of external functions.
Upvotes: 0
Views: 3119
Reputation: 3294
If you want to store ptr in pool then should you have a pool of addresses instead?
char *pool[1000];
Then
pool[0] = ptr;
ptr = pool[0];
etc.
If you have to deal with a buffer of characters, that is
char pool[1000];
but treat it as a buffer of addresses then bend it by creating a local variable:
char **pp = reinterpret_cast<char**>(&pool);
*pp = ptr;
The later stores ptr at the start of the buffer pool. To retrieve it:
ptr = *pp;
You may move along the pool by incrementing the pointer pp
pp++ // next address
And don't make an assumption that address is 4 bytes!
Upvotes: 0
Reputation: 206607
To store the value of ptr
in pool
, use:
memcpy(pool, &ptr, sizeof(ptr));
To retrieve the value of the pointer from pool
, use:
memcpy(&ptr, pool, sizeof(ptr));
Re:
This operation will happen frequently so it needs to be fast...and of course not rely of external functions.
memcpy
is exactly what you need. If you cannot use memcpy
, you'll need to implement the exact functionality in your code.
Unless you are able to verify that the calls to memcpy
is a performance bottleneck, I would advise using it.
Upvotes: 1