概述
结构体数组和结构体的嵌套
结构体数组
#include <stdio.h>
#include <string.h>
struct Student
{
int age;
char name[50];
int score;
};
int main(int argc, char const *argv[])
{
//结构体数组的初始化
struct Student a[5] =
{
{18, "mike", 59},
{19, "jiang", 66},
{33, "xiaobai", 82},
{28, "lily", 77},
{30, "xiaoan", 80}
};
int n = sizeof(a)/sizeof(a[0]);
int sum = 0;
for (int i = 0; i < n; ++i)
{
sum += a[i].score
}
printf("平均分:%dn", sum/n);
return 0;
}
int main01(int argc, char const *argv[])
{
struct Student a[5];//结构体数组
//操作元素
a[0].age = 18;
strcpy(a[0].name, "mike");
a[0].score = 59;
//操作某个元素地址
(a+1)->age = 19;
strcpy((a+1)->name, "jiang");
(a+1)->score = 60;
//操作元素
( *(a+2) ).age = 20;
strcpy(( *(a+2)).name, "lily");
( *(a+2)).score = 61;
//用指针访问
struct Student *p = a;
p = &a[0];
p[3].age = 21;
strcpy(p[3].name, "xiaoming");
p[3].score = 62;
(p+4)->age = 22;
strcpy((p+4)->name, "xiaojiang");
(p+4)->score = 88;
int i = 0;
int n = sizeof(a)/sizeof(a[0]);
for(i = 0; i < n; i++)
{
printf("%d, %s, %dn", a[i].age, a[i].name. a[i].score);
}
return 0;
}
结构体的嵌套
#include <stdio.h>
#include <string.h>
struct Info
{
int age;
char name[50];
}
struct Student
{
struct Info info;
int score;
};
int main(int argc, char const *argv[])
{
struct Student s;
s.info.age = 18;
strcpy(s.info.name, "mike");
s.score = 59;
struct Student *p = &s;
p->info.age = 18;
strcpy(p->info.name, "mike");
p->score = 59;
struct Student tmp = {18, "mike", 59};
printf("%d, %s, %dn", tmp.info.age, tmp.info.name, tmp.score);
return 0;
}
最后
以上就是超级便当为你收集整理的结构体数组和结构体的嵌套的全部内容,希望文章能够帮你解决结构体数组和结构体的嵌套所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复