2

Please see the following code snippet:

void foo(char str[][MAX_SIZE])
{
    strcpy(str[0], "Hi");
    strcpy(str[1], "Hey");
}

int main(void) {
    int V = 2;
    char str[V][MAX_SIZE];

    foo(str);

    int i;
    for(i = 0; i < V; ++i)
        printf("%s\n", str[i]);

    return 0;
}

The output is as expected:

Hi    
Hey

When the definition of foo is changed to:

void foo(char *str[MAX_SIZE]) { ... } <------------- Runtime error

It flashes Runtime error

However, wrapping the pointer in brackets works fine:

void foo(char (*str)[MAX_SIZE]) { ... } <-------------- Works fine

I guess I am getting confused between the different ways to pass a 2D array to a method.

Can you please help me understand what each definition of foo() means, what does it expect and how does it deal with the param it accepts?

Green goblin
  • 9,898
  • 13
  • 71
  • 100
  • With `void foo(char *str[MAX_SIZE]) { ... }` the code is illegal. Your compiler should tell you this; pay attention to the compiler messages. Even if something only says "warning" treat it as an error unless you are really sure that it's OK (which it is not in this case). – M.M Oct 26 '15 at 21:32
  • Check this out: http://stackoverflow.com/questions/859634/c-pointer-to-array-array-of-pointers-disambiguation – yati sagade Oct 26 '15 at 21:32
  • @M.M: I was experimenting with the things on ideone.com, and it didn't compalin and instead flashed runtime error. I have worked on other compilers and they always complained if something wrong like this is done – Green goblin Oct 26 '15 at 21:36
  • 1
    ideone is not very good really, for exactly this reason – M.M Oct 26 '15 at 21:36

2 Answers2

5

These two have the same signature, and are equivalent function declarations (after parameter adjustment):

void foo(char str[][MAX_SIZE]);
void foo(char (*str)[MAX_SIZE]);

In both, str is a pointer to an array of MAX_SIZE chars. This,

void foo(char *str[MAX_SIZE]);

however, is a function whose parameter, after adjustment, is pointer to pointer to char, i.e. equivalent to

void foo(char **str);
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • 2
    *This, however, is a function whose parameter is an array of MAX_SIZE pointers to char* it should be mentioned that here also the parameter is adjusted to a pointer type. – ouah Oct 26 '15 at 21:41
  • @ouah Edited. Thanks for pointing that omission out. What I had before was most misleading. – juanchopanza Oct 26 '15 at 21:51
1

When you use:

void foo(char *str[MAX_SIZE]) { ... }

it means str is an array of pointers of type char*. It is equivalent to

void foo(char** str) { ... }

When you use:

void foo(char (*str)[MAX_SIZE]) { ... }

or

void foo(char str[][MAX_SIZE]) { ... }

it means str is a pointer to character arrays of size MAX_SIZE.

R Sahu
  • 204,454
  • 14
  • 159
  • 270