2020.9.30 第13节 结构体中级篇

本文详细介绍了C语言中结构体的中级应用,包括结构体的嵌套使用,如何以结构体变量和指针作为数据成员。同时探讨了结构体在函数中的操作,如通过地址修改实参、结构体返回指针的注意事项以及如何避免使用全局变量进行增删改查操作。还讨论了结构体数组在处理表格数据时的局限性,主要体现在数组大小的固定性。
摘要由CSDN通过智能技术生成

一、结构体嵌套

学会如何

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>  //malloc
#include <string.h>
//<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;
};

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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值