简体   繁体   English

C:将“char (*)”传递给“char (*)[5]”类型参数的不兼容指针类型,但程序运行正常

[英]C: incompatible pointer types passing 'char (*)' to parameter of type 'char (*)[5]', but program works fine

I am getting the following warning:我收到以下警告:

warning: incompatible pointer types passing 'char ( )' to parameter of type 'char ( )[5]' [-Wincompatible-pointer-types] printField(field[5]);警告:不兼容的指针类型将“char ( )”传递给类型为“char ()[5]”的参数[-Wincompatible-pointer-types] printField(field[5]);

The printField function looks like this:打印字段 function 如下所示:

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:这是 function 电话:

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.如果有人可以帮助我,我将不胜感激。

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.假设get_field返回指向数组(以空字符结尾的字符串)的第一个元素(字符)的指针,那么它恰好与指向数组本身的指针相同。

If we illustrate it with a simple array:如果我们用一个简单的数组来说明:

char s[5];

Then that will look something like this in memory (with pointers added):然后在 memory 中看起来像这样(添加了指针):

+------+------+------+------+------+
| 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 .现在可以看出,有两个指针指向同一位置: &a[0]&s

&s[0] is what using the array decay to, and it's the type char * . &s[0]是使用数组衰减到的,它是char *类型。

&s is a pointer to the array itself, and have the type char (*)[5] . &s是指向数组本身的指针,类型为char (*)[5]

When we apply it to your case, field is the first pointer, it points to the first element of an array.当我们将它应用于您的情况时, field是第一个指针,它指向数组的第一个元素。 Which happens to be the same location as the pointer to the array itself which is what printField expects.这恰好与指向数组本身的指针位于同一位置,这正是printField所期望的。

That's the reason it "works".这就是它“有效”的原因。 But you should not do like that, you should fix the function to take an char * argument instead:但是您不应该那样做,您应该修复 function 以采用char *参数:

void printField(char *field);

The types are different.类型不同。

  • char *ptr; declares the pointer to char声明指向char的指针
  • char (*ptr)[5]; declared the pointer to an array of 5 characters .声明了指向5 个字符数组的指针。

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).在您的情况下,两个指针都指向 memory 中的同一个位置(这就是程序运行的原因)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM