C语言struct小知识

时间:2023-11-27 15:39:14

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

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

 /* makepoint: make a point from x and y components */
struct point makepoint(int x, int y)
{
struct point temp;
temp.x = x;
temp.y = y;
return temp;
}

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

 struct point addpoint(struct point pt1, struct point pt2)
{
pt1.x += pt2.x;
pt1.y += pt2.y;
}