Search code examples
arrayscimplicit-conversionc-stringsfunction-declaration

gcc C17 return from incompatible pointer type


char *funArr(char *s[]){
    return s;
}


int main(void){ 
    char *s[] = {"a","b"};
    char *r = funArr(s);
    printf("%s",r[0]);
}

I can't get an array from a function correctly. I know what the problem is, but I don't know how to solve it. I'm just getting started with C, can anyone help me?


Solution

  • A function parameter having an array type is adjusted by the compiler to pointer to the array element type.

    So this function declaration

    char *funArr(char *s[]){
    

    is adjusted by the compiler to

    char *funArr(char **s){
    

    As you see the parameter s has the type char **. If you want to return this pointer then the function return type shall be char **.

    char ** funArr(char *s[]){
    

    So in main you need to write

    char **r = funArr(s);
    printf("%s",r[0]);
    

    Here is your updated program.

    #include <stdio.h>
    
    char ** funArr( char *s[] )
    {
        return s;
    }
    
    
    int main(void)
    { 
        char * s[] = { "a", "b" };
        
        char **r = funArr( s );
        
        puts( r[0] );
    }
    

    The program output is

    a