Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
这段C代码为什么要编译?C结构类型定义_C_Compiler Construction_Struct - Fatal编程技术网

这段C代码为什么要编译?C结构类型定义

这段C代码为什么要编译?C结构类型定义,c,compiler-construction,struct,C,Compiler Construction,Struct,我编写了以下程序: typedef struct blahblah { int x; int y; } Coordinate; int main () { Coordinate p1; p1.x = 1; p1.y = 2; //blah blah has not been declared as a struct, so why is it letting me do this? struct blahblah p2; p2.x = 5;

我编写了以下程序:

typedef struct blahblah {
    int x;
    int y;
} Coordinate;

int main () {
   Coordinate p1;
   p1.x = 1;
   p1.y = 2;

   //blah blah has not been declared as a struct, so why is it letting me do this?
   struct blahblah p2;
   p2.x = 5;
   p2.y = 6; 
}
谁能给我解释一下发生了什么事吗?

你说:

blah blah未声明为结构

事实上,它有:

typedef struct blahblah {
    int x;
    int y;
} Coordinate; 
这既是一个typedef
坐标
,也是一个
struct blahblah
的定义。定义是:

  • 定义名为
    struct blahblah
  • 它有两个成员,
    intx
    inty
  • 另外,创建一个名为
    Coordinate
    的类型定义,它相当于
    struct blahblah

您在typedef中将blahblah声明为结构。typedef只是引用struct blahblah的一种简单方法。但是struct blahblah存在,这就是为什么可以给它一个typedef

您的结构声明相当于

struct blahblah {
    int x;
    int y;
};
typedef struct blahblah Coordinate;

由于这会为结构类型(
struct blahblah
)和
Coordinate
)创建两个名称,因此这两个类型名称都可以用于声明变量。

typedef
定义新的用户定义数据类型,但不会使旧定义无效。例如,
typedef int
不会使
int
无效。同样,您的
blahblah
仍然是一个有效的定义结构!坐标只是一种新类型

typedef用于创建一种类型到另一种类型的别名。实际上,您是在typedef本身中声明“struct blahblah”。这有点令人困惑,但正如@Timothy和其他人指出的,这是一个有效的定义

我不太明白<代码>结构blahblah当然已经声明为结构,它就在示例的顶部。