关于【结构体】的知识点
结构体 struct 又可以称之为自定义数据类型
举例:
定义一个结构体
struct Student
{
char name[20];
int age;
};
使用
int main()
{
struct Studnet stu1;
}
对此结构体进行一些使用测试如下:
sturct A
{
struct Student a;//ok
sturct A b;//error
struct A *p;//ok
};
以上结果说明:
结构体不能定义一个自身的普通成员变量,但是可以定义一个指向自己的指针~
知识点:
有两个自带‘*’的符号: '[ ]' 和 '->'
结构体的使用举例:
#include<stdio.h>
struct Student
{
char name[20];
int age;
};
void Show(struct Student stu)
{
printf("姓名:%s,年龄:%d\n",stu.name,stu.age);
}
int main()
{
struct Student stu1;
struct Student stu2={"fyw",20};
struct Student stu3={"whx"};//自己初始化age=0,因为聚合类型若为初始化,自定义为0
Show(stu2);
//若想要给stu3中的age赋值,用“.”来进行访问
stu3.age=23;
Show(stu3);
}
可见以上代码中stu3进行了一些传值
可以发现,whx的年龄通过stu3.age=23发生了改变
结构体普通变量通过‘.’来进行访问
修改姓名:
//想要修改whx的姓名
strcpy(stu3.name,"hhh");
Show(stu3);
可以用字符串拷贝来进行赋值操作
用->修改年龄:
void Show1(const struct Student *pstu)//const目的:防止再度修改
{
printf("姓名:%s,年龄:%d\n",pstu->name,pstu->age);
}
//主函数中:
//用->修改年龄
struct Student *pstu=&stu2;
//解引用
(*pstu).age=18;//pstu->age=18,优先级. > *,所以要加()
Show1(&stu2);
最后再来一个关于结构体之间访问的问题例子哟ヽ(゚∀゚)メ(゚∀゚)ノ
struct A
{
int a;
int *b;
};
struct B
{
int c;
int *d;
struct A e;
};
int main()
{
struct B aa;
struct B *bb=&aa;
}
最后总结一下关于struct结构体的知识点(〃'▽'〃)
1、自定义数据类型,定义完成之后,等同于内置类型
2、结构体不能定义一个自身的普通成员变量,但是可以定义一个指向自己的指针
3、有两个自带‘*’的符号: '[ ]' 和 '->'
4、结构体普通变量通过“.”来进行访问,结构体指针变量通过->来访问成员
(注意优先级‘ . ’>‘ * ’,所以不要忘记在‘*’处加括号!)
这些就是关于结构体struct的知识点啦,下一条博客将关于typedef展开讨论!欢迎大家继续阅读哟(◕ᴗ◕✿)
祝大家ヾ(✿゚▽゚)ノ0 error(s),0 warning(s)