2

I'm not sure why this is happening, I think I'm doing everything correctly. Maybe someone can help point me in the right direction.

At the end of the code I got "passing argument 1 from incompatible pointer type". What is wrong?

char* fun(char **tab,int n,int m){
    char *tab1;
    tab1=malloc((n+m+2)*sizeof(char));
    /*
      */  
    return tab1;
}

int main(){
    char tab[4][6]={ {'g','h','t','e','g','d'},
                    {'j','h','y','t','r','e'},
                    {'g','h','j','y','r','t'},
                    {'y','d','s','q','w','e'} };
    fun(tab,6,4); //here got"passing argument 1 from incompatible pointer type
    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

1 Answers1

4

Array tab defined like

char tab[4][6]

when used in an expression as an argument of a function is converted to pointer to its first element. That is it has type

char ( * )[6]

You are trying to assign it to parameter declared like

char **

There is no implicit conversion from type char ( * )[6] to type char ** and moreover such a conversion would be invalid.

You could declare the function as having parameter as a pointer to a variable length array (provided that the compiler supports VLA). For example

char* fun(int n, int m, char tab[][n] );

Or you could declare the function without using VLA. For example

char* fun( int m, char tab[][6] );

Take into account that usually at first the number of rows is passed as an argument and then the number of columns. In your function declaration you are passing at first the number of columns 6.

Here is a demonstrative program that shows how VLA can be declared as a function parameter.

#include <stdio.h>

void f( size_t n, size_t m, char tab[][m] )
{
    for ( size_t i = 0; i <n; i++ ) printf( "%s", tab[i] );
    printf( "\n" );
}   

#define N   3
#define M   11

int main(void) 
{
    char tab[N][M] = 
    {
        "new",
        "bie",
        "programmer",
    };

    f( N, M, tab );

    return 0;
}

The output is

newbieprogrammer
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335