结构体
#include<stdio.h>
**1.结构体,自定义数据类型****
struct Date
{
int year;
int mon;
int day;
}
struct Student
{
char name[20];
int age;
struct Date bir;
}
int main()
{
struct Student stu={"liubei",29};
**2.结构体普通变量通过“.”访问其成员**
stu.bir.year=1990;
struct Student *ps=&stu;
**3.结构体指针变量通过“->”访问其成员**
//通过ps定义月日5,3
ps->bir.mon=5;
ps->bir.day=3;
//输出stu所有数据
printf("%s,%d,%d-%d- %d\n",stu.name,stu.age,stu.bir.year,stu.bir.mon,stu.bir.day);
printf("%s,%d,%d,%d,%d\n",ps->name,ps->age,ps->bir.year,ps->bir.mon,ps->bir.day);
}
4.聚合类型(数组,结构体) 如果只初始化一部分,则剩下的部分为0
#include<stdio.h>
struct Student
{
char name[20];
int age;
}
int main()
{
struct Student stu={"liubei"};**//只初始化了一部分**
printf("%s ,%d\n"stu.name,stu.age);
}
运行结果:
若用函数解决:
#include<stdio.h>
struct Student
{
char name[20];
int age;
}
void Show(const struct Student *ps)
{
printf("%s,%d\n",ps->name,ps->age);
}
int main()
{
struct Student stu={"liubei"};
Show(&stu);
}
相关例题
将liubei的年龄改为25,并将数组arr的数据全部输出
#include<stdio.h>
struct Student
{
char name[20];
int age;
}
int main()
{
struct Student arr[]={"liubei",23,"sunquan",18,"caocao",24};
arr[0].age=25;
for(int i=0;i<sizeof(arr)/sizeof(arr[0]));
{
printf("%s,%d\n",arr[i].name,arr[i].age);
}
}
**
用函数表示
#include<stdio.h>
struct Student
{
char name[20];
int age;
}
void Show(const struct Student *arr,int len)
{
int i;
for(i=0;i<len;i++)
{
printf("%s,%d\n",arr[i].name,arr[i].age);
}
}
int main()
{
struct Student arr[] = {{"liubei",23},"sunquan",18,"caocao",24};
arr[0].age = 25;
Show(arr,sizeof(arr)/szeof(arr[0]));
}