结构体的初步应用
结构体的六种不同表达形式:
第一种,也就是最常用的。struct node{
int a;//结构体内可以定义整型,浮点型,字符型,字符串,当然,各种数组也可以定义。
char b;
double c;
};//这个分号一定不能漏。
第二种,struct node{
int a;
char b;
double c;
} name;
这个和第一个不同的地方在于,第一个在main函数内使用时,还需要再定义一回,而第二个不需要。
eg;
#include <stdio.h>
#include <string.h>
struct Books { char title[50];
char author[50];
char subject[100];
}; /* 函数声明 */
int main( )
{
struct Books Book1; /* 声明 Book1,类型为 Books */
struct Books Book2; /* 声明 Book2,类型为 Books */
在这里需要从新声明,这是第一种。
第二种不需要这一步,结构体最后的分号前就是结构体名称。
第三种定义方法:typedef struct
{
定义的内容;
}stu;
typedef 是一种新的定义方法,其实与直接定义没什么区别。不,其实还是有区别的。
struct是结构体的关键字,用来声明结构体变量如 struct student { char num[10]; char name[20]; int age; };
typedef是用来定义新的类型名来代替已有的类型名, 可将上面的结构体定义为 typedef struct student { char num[10]; char name[20]; int age; }stud;
也就是说,将原来的struct student 重新定义为 stud; 举个例子 如上面的方法定义了结构体student时,
如果在主函数中声明结构体变量时,应按如下方法 struct student stu[10];这样就声明了一个结构体数组,
如果开始定义时用typedef,那么就可以直接用 stud stu[10]来声明, 这就他们的区别,每必要细分。
一个新手刚上路,要有错误,请包涵。

浙公网安备 33010602011771号