The following C++ Win32 console program assigns an array to a pointer to void, and prints the results in two different ways:
// Foo.cpp : A Win32 console application.
//
#include "stdafx.h"
typedef unsigned char elem_type;
#define ELEM_COUNT 4
int _tmain(int argc, _TCHAR* argv[])
{
elem_type *ary = new elem_type[ELEM_COUNT];
for (int i = 0; i < ELEM_COUNT; i++)
{
ary[i] = ((i + 1) * 5); // multiples of 5
}
void *void_ary = ary;
for (int i = 0; i < ELEM_COUNT; i++)
{
printf("void_ary[%d] is %u\t", i, ((elem_type*)void_ary)[i]);
printf("*(void_ary+%d) is %u\n", i, *((elem_type*)(void_ary))+i);
}
void *allocd_ary;
return 0;
}
Here is the output:
void_ary[0] is 5 *(void_ary+0) is 5
void_ary[1] is 10 *(void_ary+1) is 6
void_ary[2] is 15 *(void_ary+2) is 7
void_ary[3] is 20 *(void_ary+3) is 8
Using square brackets prints the result that I expected. But dereferencing pointer offsets does not, even though the array is being typecast.
Why the discrepancy?
Well that is because you are dereferencing the value then adding ‘i’ to the result. You need some more parenthesis around the pointer cast or using static_cast which is more obvious.
As in:
*(static_cast<elem_type*>(void_ary)+i)