As a newbie, I'm solving a problem from K&R's pointers chapter and was confused with some aspects of character pointers, and passing an array of type char* as a function parameter.
Char array decay I understand
Ex:
void main( )
{
char a[ ] = "Howdy";
tryMe(a);
}
so here function parameter passed is &a[0]
void tryMe( char* s )
{
printf("value I need: %c \n", *s);
}
So this would be s = &a[0];
Now using the above understanding, I tried to do the same for an array of type char*. with the same function tryMe(char*)
Ex::
char a[ ] = "Howdy";
char b[ ] = "Doodie";
char* a1 = a;
char* b1 = b;
char* AP[ ] = { a1 , b1 };
// now to pass array AP into the function tryMe::
tryMe(AP);
This is where I get a warning saying:
warning: passing argument 1 of ‘tryMe’ from incompatible pointer type [-Wincompatible-pointer-types]
Im not sure what is going on, but I did get it working fine by doing the following thing:
changing function defintion from
tryMe(char*) to tryMe(char**)
and this works fine.
The other solution that works is:
Function definition remains same::
void tryMe(char*)
but while passing the function parameter it goes as follows::
void tryMe( char* s[ ] )
{
;
}
Though these above changes work as I want them to, I'm lost as to why are they working
I would really appreciate any guidance on these.
char* AP[ ] = { a1 , b1 };definesAPto be an array containing twochar *. SoAPis not an array ofchar. IntryMe(AP);, the arrayAPis converted to a pointer to its first element,&AP[0]. Since its first element is achar *, the pointer to it has typechar **.A
char **is unsuitable to pass as an argument for a parameter of typechar *, so the compiler complains.To pass one of the arrays (by pointer to its first element), you could use
tryMe(AP[0])ortryMe(AP[1]).If you change the function definition to have a parameter of type
char **, then, saychar **x, when you passAP, the function will receive a pointer to the first element ofAP. To get to the characters in the relevant array, it will have to dereference the pointer multiple times:xis a pointer to achar *,*xis thechar *, and**xis a character.Alternately,
xis a pointer to the first element of the array,x[0]andx[1]are thechar *elements in that array,x[0][0]is the first character of the string pointed to by the firstchar *,x[1][4]is the fourth character of the string pointed to by the secondchar *, and so on.