idealistikz
idealistikz

Reputation: 1267

Initializing and accessing a pointer from an array of pointers

Suppose I have the following:

void **Init(int numElems)
{
   //What is the best way to initialize '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?

Upvotes: 0

Views: 180

Answers (2)

nategoose
nategoose

Reputation: 12382

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.

Upvotes: 0

sth
sth

Reputation: 229563

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;
} 

Upvotes: 1

Related Questions