views:

385

answers:

4

I was under the impression that they were the same thing. However, it looks to my like they are being treated differently here. The part I am confused about looks like this.

Foo* initFoo(char* name);

int main
{
  Foo* foo;
  char* player_name[25];
  scanf("%s", player_name);
  foo = initFoo(player_name);
}

Foo* initFoo(char* name)
{
  printf("\n%s", name);
}

The string prints out fine. However, I get a compiler warning that says: passing argument 1 of 'initFoo' from incompatible pointer type.

What am I missing about pointers?

+7  A: 

A string is an array of characters. What you have here is an array of pointers to characters.

1800 INFORMATION
If you put the method to correct I will delete my answer.
ojblass
+3  A: 
char* player_name[25];  /* means an array of character pointers. */
char  player_name[25];  /* will get rid of the warning */
ojblass
A: 

To fix it change to:

char player_name[25];
sipwiz
+5  A: 

The line:

char* player_name[25];

allocates a 25 element array of pointers to char. A pointer to char is generally considered a string, so this declaration could be interpreted as an array of strings, but the memory for storing those strings does not exist yet. You would have to allocate those string separately.

Assuming pointers are 4 bytes on your machine, this line would have the effect of allocating 25 x 4 = 100 bytes.

In C, when you use an array name without a subscript, it "decomposes" into a pointer to the first element of the array.

So... when this line is executed:

scanf("%s", player_name);

player_name points to 100 bytes of memory, enough room enough to hold 100 characters that are read in (well 99 characters plus a terminating NUL byte). The compiler is not protecting you from storing those characters in the memory that was allocated for 25 pointers.

Finally:

foo = initFoo(player_name);

is passing the starting address of the array to the function initFoo(). The compiler knows this is probably wrong since initFoo() is supposed to take a pointer to chars, not at pointer to an array of char pointers, but it lets you do it anyway except for the warning. The printf() statement in initFoo() reinterprets that pointer as a char pointer, and you get the correct results!

As others have said, it would be correct to change the one line to

char player_name[25];

which declares an array of 25 characters.

Jeremy