今天看到这样的写法,有点蒙,如下
static struct
{
char a;
char b;
} hrpsCb;
测试程序如下
#include <stdio.h>
static struct
{
char a;
char b;
} hrpsCb;
int main()
{
hrpsCb.a = 1;
hrpsCb.b = 2;
printf("Hello, World! %d %d\n",hrpsCb.a,hrpsCb.b);
return 0;
}
结果如下
其实上述写法是在构造结构体类型同时声明了一个结构体变量,是占用内存的,并修饰为static
注意要和如下typedef区分
typedef struct
{
char c;
char d;
} hrpsConn_t;
这是用typedef给此结构体类型取别名,本质还是构造结构体,不占内存,要做好区分。
struct总结如下
构造结构体类型,不占内存
struct 结构体名{
结构体成员
}
如
struct stu{
char *name; //姓名
int num; //学号
int age; //年龄
char group; //所在学习小组
float score; //成绩
};
用这个类型定义stu1, stu2变量,占用内存
struct stu stu1, stu2;
上面2步可以合在一起,定义结构体的同时定义结构体变量
struct stu{
char *name; //姓名
int num; //学号
int age; //年龄
char group; //所在学习小组
float score; //成绩
} stu1, stu2;
如果后面不在需要定义其他struct stu类型变量,则结构体名可以省略,如下
struct{ //没有写 stu
char *name; //姓名
int num; //学号
int age; //年龄
char group; //所在学习小组
float score; //成绩
} stu1, stu2;
,只不过例子用static修饰