I have a function that takes pointer to pointer to struct.
struct ABC;
void func(ABC ** ptr); //func is provided by someone else and i don't know about the implementation. { }
Now, i have following code.
ABC xyz[2]; ABC * ptr = xyz; ABC **dptr1 = &ptr; //pointer to ponter ABC ** dptr2 = (ABC **)malloc(2*sizeof(struct abc*)); //pointer to arrary of pointers dptr2[0] = &xyz[0]; dptr2[1] = &xyz[1];
if i pass dptr1 to func, and func does something like *ptr[0] and *ptr[1] to access the actual values, it fails.
So, what is the standard way of passing around a double pointer.
When you pass
ptr1tofunc, you are actually passing a pointer to the memory occupied byptr. The problem is thatfuncseems to be assuming thatptr1is actually pointing the beginning of an array of pointers, but you’ve passed it a pointer to an ‘array’ of only one pointer,ptr.funcwill probably do major damage on your stack.What you should do when passing a pointer into a function is to determine whether that function will be treating the pointer as just that, or as a pointer into an array (which seems to be the case with func here). In the latter case, you have to be careful to indeed provide an array for the function.
In your code, I would write
As an aside, because C doesn’t have a notion of array parameters, it is usually a good idea to specify an additional parameter with the array length in question, or you may leave yourself open to buffer overflow vulnerabilities. Your
funcfunction could have been writtenfunc(ABC ** ppabc, int elements)to better reflect how it intends to use its parameters. The current function signature implies that func in reality will only use the pointer pointed to by the pointer to pointer (try saying that fast three times!)