简体   繁体   中英

Dynamic array and void pointers

I have quite peculiar problem. I want initialize an array pointed by a void pointer to which memory is allocated using new as shown below.

const int ARRAY_SIZE = 10;
void InitArray()
{
    int *ptrInt = new int[ARRAY_SIZE];
    for(int i=0; i<ARRAY_SIZE;i++)
    {
         ptrInt[i] = 1; //OK
    }

    void *ptrVoid = new int[ARRAY_SIZE];
    for(int i=0; i<ARRAY_SIZE;i++)
    {
         *(int*)ptrVoid[i] = 1; //Culprit  : I get a compiler error here 
                                //(error C2036: 'void *' : unknown size)
    }
}

Now, I want to initialize the elements of this array which is pointed by ptrVoid with say 1. How do I go about it? With this code I get a compiler error as shown in the code(I am using VS 2010). Any suggestions?

You have an order of operations problem (and an extra * ). Try this inside your second loop:

((int *)ptrVoid)[i] = 1;

*(int*)ptrVoid[i] is *((int*)(ptrVoid[i])) , and you're dereferencing too many times (the [] does a dereference).

Write ((int*)ptrVoid)[i] (or, better, static_cast<int*>(ptrVoid)[i] ) then re-consider your use of void* at all.

You just need to parenthesize correctly and cast the void* to an int* , so that the compiler knows how many bytes to offset when you index it with [i] .

for(int i=0; i<ARRAY_SIZE;i++)
{
     ((int*)ptrVoid)[i] = 1;
}

How about:

int* ptrVoidAsInt = new int[ARRAY_SIZE];
for(int i=0; i<ARRAY_SIZE;i++)
{
     ptrVoidAsInt[i] = 1;                               
}
void* ptrVoid = ptrVoidAsInt;

But, one has to wonder what the meaning of either a void array or 1 initialised data is. Is this really an array of int or some other type that is going to be passed as a void* and then recast back to a typed array?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM