In C, why is it that I'm able to pass character arrays to functions that take a char *
as an argument, but I cannot pass the address of an array to functions that take a char **
?
UPDATE: Interestingly, changing the argument type to char* qux[12]
doesn't change the compiler warning at all
For example:
#include <stdio.h>
void foo(char* qux) { puts(qux); }
void bar(char** qux) { puts(*qux); }
void baz(char* qux[12]) { puts(*qux); }
int main() {
char str[12] = "Hello there";
foo(str);
bar(&str); // Compiler warning
baz(&str); // Same compiler warning
return 0;
}
In the second case, I get a compiler warning:
warning: incompatible pointer types passing 'char (*)[12]' to
parameter of type 'char **' [-Wincompatible-pointer-types]
What's going on here?
Arrays naturally decays to pointers to their first element. So in the call foo(str)
it's really the same as foo(&str[0])
. This is of type char *
so it's all okay.
Now the second call, the one to bar
, is a different matter. When you use &str
you don't get a pointer to the arrays first element, you get a pointer to the array itself. And as the compiler noted, this is of type char (*)[12]
, which is very different from (and incompatible with) char **
.
Lastly, when you declare baz
you say that the argument is of type char *[12]
, that is you have an array or 12 pointers to char, not that you have a pointer to an array of 12 char
. Furthermore, due to the array decay to pointer thing, char *[12]
is actually the same as char **
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With