{Re-posted} How do you implement a parameter in C which can accept a pointer to a pointer which can point to any data type? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

{Re-posted} How do you implement a parameter in C which can accept a pointer to a pointer which can point to any data type?

void k(void** p) { // TEST return; } int main() { int a = 6; int* p = &a; k(&p); // Shows a warning }

9th May 2021, 9:10 AM
Calvin Thomas
Calvin Thomas - avatar
5 Answers
+ 2
Just cast &p to void** explicitly. k( (void**) &p );
9th May 2021, 9:50 AM
XXX
XXX - avatar
+ 2
@Martin Taylor You are correct. But I just wanted to point out that the OP is asking about C, not C++. So the C compiler gives a warning, unlike the C++ compiler which gives an error.
9th May 2021, 11:50 AM
XXX
XXX - avatar
+ 1
Martin Taylor Thank you for the explanation. It really helps.
10th May 2021, 1:56 AM
Calvin Thomas
Calvin Thomas - avatar
0
XXX and Martin Taylor Thanks for answering my question. But why in the first place does my code show a warning, i.e., why can't I pass a pointer to an int pointer as the argument to the void** parameter? @Martin Taylor, why did you typecast the resultant pointer of each of the variables to a void pointer, as the void pointer 'p' just stores the memory location and '&a' returns exactly that?
9th May 2021, 10:42 AM
Calvin Thomas
Calvin Thomas - avatar
0
Martin Taylor Thank you for the explanation, and the code bits. However, my question remains unresolved. Framing it again, why does C raise a warning, if a pointer to an int pointer (or a char pointer) is provided as the argument to the function 'k' containing void** as it's parameter? Why typecast it first, as a pointer which points to another pointer pointing to an undefined type should in theory accept another pointer to an int pointer? Is there a reason for this or is it that C was made to function like this?
9th May 2021, 2:44 PM
Calvin Thomas
Calvin Thomas - avatar