0

I want to get char* array as parameter in C function. I using by this code:

void func(char* str, char *res[])
{
  res[0]=strstr(str,"str");
  ....
}

int main()
{
   char *res[6];
   func(str,res);
...
}

As far as I know, array sent to function as pointer, so I don't know why I get an compilation error:

Argument of type char(*)[6] is incompatible with parameter of type char**

How should I correct my code?

2 Answers2

1

I'm afraid your problem is somewhere else, as I compiled the following code successfully:

void
func(char* str, char *res[])
{
}

int
main()
{
    char *res[6];

    func("test", res);

    return 0;
}

I compiled it using the following command:

gcc -o tmp.o -c tmp.c -Wall -Werror -pedantic

I think the formal and actual argument types are perfectly legal here, despite the other answers.

Pavel Šimerda
  • 5,783
  • 1
  • 31
  • 31
-2

You should do either char** ary or char* ary[5] (for an array with length 5) in your function argument.

The first syntax passes a pointer to a pointer, which means you can place a array of pointers in the memory and pass a pointer to it to your function. Note that you should pass the length of your array in a second parameter, to be able to loop over it. Or you could set the last pointer in the array to NULL, and loop until you hit that. If you do that, you cannot pass an array which contains NULL pointers, as you don't know when to stop.

The second syntax is for passing a fixed-sized array of pointers to your function.

musicmatze
  • 4,124
  • 7
  • 33
  • 48
  • Those two syntaxes are exactly equivalent (and neither is what OP requested). [see this](http://stackoverflow.com/questions/22677415/why-do-c-and-c-compilers-allow-array-lengths-in-function-signatures-when-they/) – M.M Apr 06 '14 at 11:22
  • Nope, they're not. The first syntax can be used to pass an array of pointers with length `n`. With the second syntax, the compiler checks that the length of the passed array is 5. – musicmatze Apr 07 '14 at 09:50
  • No it doesn't . Try it – M.M Apr 07 '14 at 09:53