Home > Mobile >  C: incompatible pointer types passing 'char (*)' to parameter of type 'char (*)[5]�
C: incompatible pointer types passing 'char (*)' to parameter of type 'char (*)[5]�

Time:11-30

I am getting the following warning:

warning: incompatible pointer types passing 'char ()' to parameter of type 'char ()[5]' [-Wincompatible-pointer-types] printField(field[5]);

The printField function looks like this:

void printField(char (*field)[5])
{
...
}

and the field I am giving to it is defined as follows:

char (*field) = get_field(input);

Here is the function call:

printField(field);

Now, I do understand, that there is obviously some sort of mismatch happening, but I can't tell what to change for it not to be there anymore. I would appreciate it very much, if someone could help me.

CodePudding user response:

Assuming that get_field return a pointer to the first element (character) of an array (null-terminated string), then that happens to be the same as the pointer to the array itself.

If we illustrate it with a simple array:

char s[5];

Then that will look something like this in memory (with pointers added):

 ------ ------ ------ ------ ------ 
| s[0] | s[1] | s[2] | s[3] | s[4] |
 ------ ------ ------ ------ ------ 
^
|
&s[0]
|
&s

Now as can be seen that there are two pointers pointing to the same location: &a[0] and &s.

&s[0] is what using the array decay to, and it's the type char *.

&s is a pointer to the array itself, and have the type char (*)[5].

When we apply it to your case, field is the first pointer, it points to the first element of an array. Which happens to be the same location as the pointer to the array itself which is what printField expects.

That's the reason it "works". But you should not do like that, you should fix the function to take an char * argument instead:

void printField(char *field);

CodePudding user response:

The types are different.

  • char *ptr; declares the pointer to char
  • char (*ptr)[5]; declared the pointer to an array of 5 characters.

Those pointer types are not compatible - thus compiler warning.

In your case, both pointers refer to the same place in the memory (and that is the reason why the program works).

  • Related