c语言由于不像java,c#,c++等语言有对象,所以就用struct结构体来表示,其实作用是差不多的,下面来快速学习c语言struct结构体的定义和使用,以学生类student来举例,有三种定义方式,如下。
第一种:#include
#include
struct student{
int id;
char name;
int age;
};
//定义别名stu
struct student stu;
int main(){
//stu.id = 3;
//stu.name = "zhangsan";
//stu.age = 30;
//也可以一次性赋值
struct student stu = {2,"lisi",20};
//输出
printf("%d",stu.id);
return;
}
第二种c语言struct结构体定义方式是第一种的简写。#include
#include
struct student{
int id;
char name;
int age;
}stu;
int main(){
//stu.id = 3;
//stu.name = "zhangsan";
//stu.age = 30;
//也可以一次性赋值
struct student stu = {2,"lisi",20};
//输出
printf("%d",stu.id);
return;
}
第三种使用typedef定义结构体,注意:typedef定义的这种不可以直接使用“stu.属性”的形式赋值,以下是它的用法,并且注意有错误的那一行。#include
#include
typedef struct student{
int id;
char name;
int age;
}stu;
int main(){
//stu s相当于new对象,再用“对象.属性”的形式,如s.id,s.name。
//stu s;
//s.id = 3;
//s.name = "zhangsan";
//s.age = 20;
//也可以一次性直接赋值,类似于创建对象
stu s = {1,"lisi",15};
//输出
printf("%d",s.id);
//注意:如下stu.id形式是错误的,只能像上面的s.id = 3这样写
//stu.id = 3;
return;
}
来源网站:太平洋学习网,转载请注明出处:http://www.tpyyes.com/a/kuozhan/108.html