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

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

问题描述

当我使用此代码时,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 给出一个数组指针,一个特殊的指针类型int(*)[5],它指向整个数组.
  • arr,当用诸如 int *q = 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天全站免登陆