将指针类型转换为未定义类型不会产生编译器错误

Dai*_*ner 3 c pointers casting compiler-errors

我正在编写一个套接字程序,但我输错了struct sockaddr_inas struct sockaddrr_in(注意一个额外的r),但我没有收到任何编译器错误,只有incompatible-pointer-types警告。

这是一个演示该问题的最小可重现程序。

#include <stdio.h>

struct Addr {
    int flat_no;
};

struct Person {
    struct Addr *address;
};

int main()
{
    struct Person p;
    struct Addr addr;
    p.address = &addr;
    struct Person *ptr = &p;
    struct Addr *a = (struct Addrr *)ptr->address; // struct Addr mistyped as Addrr
    printf("no error!!");
}
Run Code Online (Sandbox Code Playgroud)

gcc都会clang产生此警告:

<source>:20:22: warning: initialization of 'struct Addr *' from incompatible pointer type 'struct Addrr *' [-Wincompatible-pointer-types]
   20 |     struct Addr *a = (struct Addrr *)ptr->address;
      |                      ^
Run Code Online (Sandbox Code Playgroud)

由于struct Addrr从未在程序中定义,编译器如何解决输入错误的符号?ptr->address类型转换为未定义类型有什么影响struct Addrr

dbu*_*ush 6

因为强制转换是第一次struct Addrr出现,所以它充当该类型的声明。该类型不完整,因为它没有定义,但您仍然可以创建指向不完整类型的指针。

因此,虽然您确实收到有关在不兼容的指针类型之间进行转换的警告,但您不会收到有关其他类型的错误。