Reputation: 378
I have this piece of code
unsigned char* MemoryPool::GetNext(unsigned char* pBlock)
{
unsigned char** ppChunkHeader = (unsigned char**)pBlock;
return ppChunkHeader[0];
}
taken from here http://gamecode4.googlecode.com/svn/trunk/Source/GCC4/Memory/MemoryPool.cpp
I don't know what the cast to unsigned char** from unsigned char* does. If I add these lines of code:
unsigned char* MemoryPool::GetNext(unsigned char* pBlock)
{
unsigned char **ppChunkHeader = (unsigned char**)pBlock;
printf("ppChunkHeader %p\n", ppChunkHeader);
printf("pBlock %p\n", pBlock);
printf("sizeof(unsigned char*) = %i\n", sizeof(unsigned char*));
printf("ppChunkHeader[0] %p\n", ppChunkHeader[0]);
printf("&pBlock[0] %p\n", &pBlock[0]);
printf("ppChunkHeader[0] - &pBlock[0] = %p\n", (ppChunkHeader[0] - &pBlock[0]));
return ppChunkHeader[0];
}
the output is
ppChunkHeader 00DCB498
pBlock 00DCB498
sizeof(unsigned char*) = 4
ppChunkHeader[0] 00DCB4A1
&pBlock[0] 00DCB4A1
ppChunkHeader[0] - &pBlock[0] = 00000009
I think it's important to mention that, in my code, pBlock points to an array of 9 elements.
Thank you.
Upvotes: 2
Views: 321
Reputation: 87959
The cast can't be understood without looking at the next line of code
unsigned char** ppChunkHeader = (unsigned char**)pBlock;
return ppChunkHeader[0];
pBlock is a block of memory, what the cast and the dereference on the next line do is take the first four bytes of that block, and treat that as another pointer. That second pointer is then returned from the function.
You can see that the cast doesn't change the value of the pointer, ppChunkHeader and pBlock are the same value. What different is how what they are pointing to is interpreted. If you wrote
return pBlock[0];
that would be just a single char, because pBlock is an unsigned char*. But ppChunkHeader[0] is an unsigned char* because ppChunkHeader is an unsigned char**.
Upvotes: 2