一、结构体嵌套
学会如何
1.以另一个 结构体变量 维为数据成员
< 1 > . 不常见的写法 定义 赋值 访问
struct A
{
int num;
struct B
{
int age;
} ;
} ;
struct MM
{
int num;
struct GG
{
int age;
} boy;
} ;
< 2 > . 常见的就是以结构体变量为成员的写法
struct score
{
int math;
int english;
} ;
struct student
{
在结构体中定义其他结构体的结构体变量
struct score stuScore;
char name[ 20 ] ;
int num;
} ;
2.以另一个 结构体指针 为数据成员
问题:这个指针没有内存,要使用的话要先申请内存,指针不能直接充当变量。 要不指向一段地址,要不申请内存当变量
struct score
{
int math;
int english;
} ;
struct studentInfo
{
struct score* pScore;
char name[ 20 ] ;
int num;
} ;
struct studentInfo* p = ( struct studentInfo* ) malloc ( sizeof ( struct studentInfo) ) ;
p-> pScore = ( struct score* ) malloc ( sizeof ( struct score) ) ;
p-> pScore-> english = 14 ;
p-> pScore-> math = 100 ;
strcpy ( p-> name, "迪丽热巴" ) ;
p-> num = 1004 ;
printf ( "%d\t%d\t%s\t%d\n" , p-> pScore-> math, p-> pScore-> english,
p-> name, p-> num) ;
结构体嵌套
1. 以另一个结构体变量为数据成员
2. 以另一个结构体指针为数据成员
学会如何使用
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct A
{
int num;
struct B
{
int age;
} ;
} ;
struct MM
{
int num;
struct GG
{
int age;
} boy;
} ;
struct score
{
int math;
int english;
} ;
struct student
{
struct score stuScore;
char name[ 20 ] ;
int num;
} ;
struct studentInfo
{
struct score* pScore;
char name[ 20 ] ;
int num;
} ;
int main ( )
{
struct A aObject = {
11 , 23 } ;
printf ( "%d\t%d\n" , aObject. age, aObject. num) ;
struct A* pA = & aObject;
printf ( "%d\t%d\n" , pA-> age, pA-> num) ;
struct MM mmObject = {
121 , 134 } ;
printf ( "%d\t%d\n" , mmObject. num, mmObject. boy. age) ;
struct student Bug = {
23 , 34 , "张三" , 1001 } ;
struct student Liu = {
{
23 , 434 } , "Liu" , 1002 } ;
printf ( "%d\t%d\t%s\t%d\n" , Liu. stuScore. math,
Liu. stuScore. english, Liu. name, Liu. num) ;
struct studentInfo* p = ( struct studentInfo* ) malloc ( sizeof ( struct studentInfo) ) ;
p-> pScore