1

I've made a function, but I'm struggling with calling it.

This is the prototype of the function:

char *test(int argc, char **argv);

I've tried calling it this way but it doesn't work :

int main()
{

    char tab[3][3] ={
     "Yo",
     "Hi"};

    test(2, tab);


  return (0);
}
Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
Exdeen
  • 13
  • 3

4 Answers4

0

For me this works:

char* test(int index, char** char2Darray)
{
    return char2Darray[index];
}

int main()
{

    char* tab[2] ={
     "Yo",
     "Hi"};

    test(1, tab);


  return (0);
}

I think there are two problems in your code :

  • the tab what you provided has only two item
  • your tab is a pointer which pointing to char[3] types and not char*
Istvan Nagy
  • 33
  • 1
  • 4
0

When you pass the 2D array

char tab[3][3]

to the function test(), it decays to a pointer of type:

char (*)[3]

which is a pointer to an array of 3 char elements.

This type is not compatible with char** which is a pointer-to-pointer to char. This is the source of your problem. You need to change the function test() to take char (*argv)[3] instead of char **argv.

machine_1
  • 4,266
  • 2
  • 21
  • 42
0

Looking at function prototype: char *test(int argc, char **argv);

char **argv is pointer of pointers and the variable char tab[3][3] is array of arrays so they are incompatible.

You can change function prototype to: char *test(int argc, char argv[][SOMECONSTANT]); or char *test(int argc, char (*argv)[3]);

patoglu
  • 401
  • 4
  • 16
-1

This way

char * test(int argc,const char **argv);

int main()
 {
  const char * tab[3]=
   {
    "Yo",
    "Hi",
    0
   };

  test(2,tab);

  return 0;
 }

or

char * test(int argc,char **argv);

int main()
 {
  char arg1[]="Yo";
  char arg2[]="Hi";

  char * tab[3]=
   {
    arg1,
    arg2,
    0
   };

  test(2,tab);

  return 0;
 }
Sergey Strukov
  • 373
  • 3
  • 9