I have a large char array which is functioning as a memory pool and want to store a pointer in the first position of the array which points to whatever the next open position in the pool is, so every time something is allocated to the pool the pointer would point to the byte that follows the ones which were just allocated. My only problem is I am not quite sure how to store the pointer in the array and then be able to modify it in other functions since the only place the pointer will exist is in the array[0] position. Can anyone point me in the right direction on this?
the char array is declared like:
char pool[size];
If you can't follow the recommendations of the other answers because you absolutely must use the pool to store all information in it, the safest way to store the integer information in the char-array is to use memcpy
(I am using C++11 syntax):
#include <cstring>
#include <iostream>
int main()
{
using size_type = std::size_t;
static constexpr size_type size = 1000;
char pool[size];
/* Store 12 as integer information at the beginning
of the pool: */
size_type next_free = 12;
std::memcpy(pool,&next_free,sizeof(size_type));
/* Retrieve it: */
size_type retrieved = 0;
std::memcpy(&retrieved,pool,sizeof(size_type));
/* This will output 12: */
std::cout << retrieved << std::endl;
return 0;
}
Of course this implies that the first sizeof(size_type)
entries of the pool must not be used to store any actual characters. The lowest entry you can actually use is pool[sizeof(size_type)]
.