C语言struct小知识

C语言struct小知识

1.C语言里的struct是不能包含成员函数的,只能有数据成员
2.C语言struct定义变量只能用一下两种方式:
struct { ... } x, y, z;
struct point pt;
直接point pt;是错误的定义;
pt3 = { 3, 5 }; //错误
pt2 = makePint(1, 1); //正确
还可以用返回值为结构体类型的函数对以声明的结构体变量赋值;不能用初始值列表给已声明的struct变量赋值。

3返回值类型为结构体的函数:

1 /* makepoint: make a point from x and y components */
2 struct point makepoint(int x, int y)
3 {
4 struct point temp;
5 temp.x = x;
6 temp.y = y;
7 return temp;
8 }

4.形参和返回值都为结构体的函数:

1 struct point addpoint(struct point pt1, struct point pt2)
2 {
3 pt1.x += pt2.x;
4 pt1.y += pt2.y;
5 }