Initializing and accessing a pointer from an array of pointers
Posted
by idealistikz
on Stack Overflow
See other posts from Stack Overflow
or by idealistikz
Published on 2010-04-27T03:52:12Z
Indexed on
2010/04/27
4:03 UTC
Read the original article
Hit count: 209
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?
© Stack Overflow or respective owner