分配给指针时从不兼容的指针类型警告进行初始化 [英] Initialization from incompatible pointer type warning when assigning to a pointer

查看:495
本文介绍了分配给指针时从不兼容的指针类型警告进行初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用此代码时,GCC会向我发出从不兼容的指针类型初始化"的警告(尽管该代码可以正常工作,并且可以执行其应做的工作,即打印数组的所有元素).

GCC gives me an 'Initialization from incompatible pointer type' warning when I use this code (though the code works fine and does what it's supposed to do, which is print all the elements of the array).

#include <stdio.h>

int main(void)
{
    int arr[5] = {3, 0, 3, 4, 1};
    int *p = &arr;

    printf("%p\n%p\n\n", p);

    for (int a = 0; a < 5; a++)
        printf("%d ", *(p++));
    printf("\n");
}

但是,当我使用这段代码时,没有给出警告

However no warning is given when I use this bit of code

int main(void)
{
    int arr[5] = {3, 0, 3, 4, 1};
    int *q = arr;

    printf("%p\n%p\n\n", q);

    for (int a = 0; a < 5; a++)
        printf("%d ", *(q++));
    printf("\n");
}

这两个摘要之间的唯一区别是,我分配了* p =& arr和* q = arr.

The only difference between these two snippets is that I assign *p = &arr and *q = arr .

  • &到底有什么不同制作?
  • 为什么在两种情况下代码都执行并给出完全相同的输出?

推荐答案

  • &arr给出了 array指针,这是一种特殊的指针类型int(*)[5],它指向整个数组.
  • 当用int *q = arr;这样的表达式编写时,
  • arr会衰减"到指向第一个元素的指针中.完全等同于int *q = &arr[0];
    • &arr gives an array pointer, a special pointer type int(*)[5] which points at the array as whole.
    • arr, when written in an expression such a int *q = arr;, "decays" into a pointer to the first element. Completely equivalent to int *q = &arr[0];
    • 在第一种情况下,您尝试将int(*)[5]分配给int*.这些是不兼容的指针类型,因此是编译器诊断消息.

      In the first case you try to assign a int(*)[5] to a int*. These are incompatible pointer types, hence the compiler diagnostic message.

      事实证明,指向第一个元素的数组指针和int指针很可能在内部具有相同的表示形式和相同的地址.这就是为什么第一个示例即使不正确的C也可以运行"的原因.

      As it turns out, the array pointer and the int pointer to the first element will very likely have the same representation and the same address internally. This is why the first example "works" even though it is not correct C.

      这篇关于分配给指针时从不兼容的指针类型警告进行初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆