What is the implicit decay of char* arrays?

193 Views Asked by At

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.

1

There are 1 best solutions below

0
On BEST ANSWER

char* AP[ ] = { a1 , b1 }; defines AP to be an array containing two char *. So AP is not an array of char. In tryMe(AP);, the array AP is converted to a pointer to its first element, &AP[0]. Since its first element is a char *, the pointer to it has type char **.

A char ** is unsuitable to pass as an argument for a parameter of type char *, so the compiler complains.

To pass one of the arrays (by pointer to its first element), you could use tryMe(AP[0]) or tryMe(AP[1]).

If you change the function definition to have a parameter of type char **, then, say char **x, when you pass AP, the function will receive a pointer to the first element of AP. To get to the characters in the relevant array, it will have to dereference the pointer multiple times: x is a pointer to a char *, *x is the char *, and **x is a character.

Alternately, x is a pointer to the first element of the array, x[0] and x[1] are the char * elements in that array, x[0][0] is the first character of the string pointed to by the first char *, x[1][4] is the fourth character of the string pointed to by the second char *, and so on.