I recently came across some code on stackoverflow where pointers to pointers where used to change allocated memory. While checking the code I made the mistake to add an ampersand to a pointer so make a pointer to a pointer still the compiler happily compiled and runtime errors occured. As an example
#include <stdio.h>
void func(int **p) {
printf("Pointer is at %p\n", p);
}
int main(void) {
int *p = 0;
func(p);
func(&p);
int **pp = &p;
func(&pp);
return 0;
}
I do understand that C has significantly lower restrictions for pointers than C++ and allows something like char *buf = malloc(SIZE)
while not allowed in C++. I see it as a convenience because it happens so much in C.
Nevertheless, I think that the amount of references is a great source of errors and I wonder why one might allow this especially since int
is different from int*
. Furthermore I want to know if the C standard says something about this.
EDIT I compiled it under ideone.com which likely does not show warnings. My local clang compiler as well as gcc do give warnings. Still, why are they just warnings when they represent different things.
PS, I feel like something like this should have been asked in the last six years of SO. If this a duplicate I am sorry for not finding one.
The conversion is not legal. More precisely, there is no implicit conversion from
int*
toint**
, or fromint***
toint**
. Attempting to pass anint*
or anint***
to a function that requires anint**
argument is a constraint violation; any conforming compiler must diagnose it. (The diagnostic message may be a non-fatal warning.)When I compile your code with gcc, even with default options (which makes gcc non-conforming), I get several warnings:
I don't know why ideone doesn't complain about it (http://ideone.com/uzeXur).