1。定义方法(简单,不推荐)
struct { int x, y} point ;
这种定义结构体的方法,没有办法再次引用这个结构体了,因为它没有名字。只能是使用一个变量point了
2。struct point { int x, y} point1 ; ( 推荐 )
这种方法可以直接使用变量 point1,并且向后,还可以使用 struct point point2 来定义变来那个。
可以在定义时,初始化,struct complex_struct z = {3.0, 4.0}; 但是如果不是在定义时,这种做法是错误的。例如 struct complex_struct z1 ; z1 = {3.0 , 40}; //这个代码是错误的
3。typedef 定义结构体 ( 一般推荐 )
typedef定义结构体#include <stdio.h> typedef struct point{ int x; int y; }p; typedef struct { int x; int y; }q; int main(void) { p a; q b; a.x = 1; a.y = 1; b.x = 2; b.y = 2; p.x = 3; // wrong q.y = 3; // wrong printf("a.x=%d,a.y=%d\nb.x=%d,b.y=%d",a.x,a.y,b.x,b.y); getchar(); return 0; }
以上2个使用 typedef的方法,定义结构体,可以使用 p , q 来定义结构体,原理参考如下说明,但是同时定义,此时的 p , q 已经不是结构体变量,而是结构体定义的名称,所以它们不能再直接使用 . 操作符,例如上面程序的 p.x = 3; 和 q.y = 3 编译时是会出错的,因为找不到该变量。
类型定义符 typedef :作用为类型起别名,例如 typedef char NAME[20] , NAME a1,b1,c1 ; 为什么使用NAME 定义 ?因为数组的名字为NAME , 而 typedef 的作用就时名字替换定义。例如定义 typedef char NAME[20] , 定义应该为 char NAME[ 20 ]定义的名称为NAME,那么使用 NAME a,b,c ; 定义的内容 : a 是一个char 型的数组(20长度). 因为用NAME定义,就相当于用 char a[20] .