Initializing and accessing a pointer from an array of pointers

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?

Seg Fault with malloc'd pointers


Is this a memory leak?
The initialization should job this way, just remember to free() the memory again once you are done with it.. What are void pointers for in C++? To receive the address of a specific element you must use normal array index access toreceive her with the address-of operator &:. Mmap and structure
void **GetPtr(void **ptrElems, int index) {     void **elem = &ptrElems[index];     return elem; }  
A question on vectors, pointers and iteratorsCan we overload the Point object in C# so it supports doubles?


what is meant by normalization in huge pointers
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, although then you would have to test the return value before zeroing the memory in case malloc failed.. C pointer question, dereferencing crash sth's answer would job for the next part, although so would:.
void **GetPtr(void **ptrElems, int index) {     return ptrElems + index; }  
When you add an integer to a pointer C assumes this you want the integer to be like an array index and adds sizeof whatever it points to times the integer. This is why you must ++ or -- a pointer and receive a pointer to the next or previous element..

48 out of 100 based on 18 user ratings 488 reviews