tags:

views:

58

answers:

2

Suppose I have the following:

void **Init(int numElems)
{
   //What is the best way to intialize 'ptrElems' to store an array of void *'s?
   void **ptrElems = malloc(numElems * sizeof(void *));
   return ptrElems;
}

//What is the best way to return a pointer pointing at the index passed as a parameter?
void **GetPtr(void **ptrElems, int index)
{
    void **elem = elems + (index * sizeof(void *)); 
    return elem;
} 

First, what is the best way to intialize 'ptrElems' to store an array of pointers? I use malloc because assigning it to an array will not persist after the end of the function.

Second, what is the best way to point to the pointer at the specified index? I tried typecasting the first line of the 'GetPtr' function to ensure proper pointer arithmetic, but I receive the warning, 'initialization from incompatible pointer type'. Is it necessary to typecast?

+1  A: 

The initialization should work this way, just remember to free() the memory again once you are done with it.

To get the address of a specific element you can use normal array index access together with the address-of operator &:

void **GetPtr(void **ptrElems, int index)
{
    void **elem = &ptrElems[index];
    return elem;
} 
sth
caf
Is malloc the best way to initialize a 'void **' to point to an array of pointers?
idealistikz
A: 
void **Init(int numElems)
{
   //  This allocates the memory and sets it to 0 (NULL)
   void **ptrElms = calloc(numElems * sizeof(void *) );
   return ptrElems;
}

You could also call memset or bzero on the memory after you allocate it, which would have the same result, but then you would have to test the return value before zeroing the memory in case malloc failed.

sth's answer would work for the next part, but so would:

void **GetPtr(void **ptrElems, int index)
{
    return ptrElems + index;
} 

When you add an integer to a pointer C assumes that you want the integer to be like an array index and adds sizeof whatever it points to times the integer. This is why you can ++ or -- a pointer and get a pointer to the next or previous element.

nategoose
`calloc` takes two values and does the multiplication for you
R Samuel Klatchko