结构体和malloc学习笔记

结构体学习:

为什么会出现结构体:

为了表示一些复杂的数据,而普通的基本类型变量无法满足要求;

定义:

结构体是用户根据实际需要自己定义的符合数类型;

如何使用结构体:
cpp 复制代码
//定义结构体
struct Student
{
    int sid;
    char name[200];
    int age;
};

//1.整体赋值
struct Student st = {1001,"zhangsan",18};

//2.单个赋值
st.id = 1001;
strcpy(st.name,"zhangsan");
st.age = 18;

//3.指针方式赋值
struct Student *pst;
pst->sid = 1001;
strcpy(pst->name,"zhangsan");
pst->age = 18;
注意事项:

结构体变量不能算数计算,但是可以相互赋值;普通结构体变量和结构体指针变量作为函数传参的问题,推荐使用传递结构体指针的方式,这样效率高节约内存

malloc学习:

示例代码:

cpp 复制代码
#include <stdio.h>
#include <malloc.h>

int main(void)
{
    int len;
    char a[5] = {1,2,3,4,5};
    printf("请输入你要创建的数组长度:len = ");
    scanf("%d",&len);
    int * pArr = (int *)malloc(sizeof(int) * len);
    for (int i = 0; i < len; i++)
    {
        scanf("%d",&pArr[i]);
    }
    for (int i = 0; i < len; i++)
    {
        printf("%d\n",pArr[i]);
    }
    free(pArr);
    
    return 0;
}

运行结果:

跨函数使用内存:

cpp 复制代码
#include <stdio.h>
#include <malloc.h>

struct Student
{
    int sid;
    int age;
};
struct Student * creatlist()
{
    struct Student * ps = (struct Student *)malloc(sizeof(struct Student));
    ps->age = 99;
    ps->sid = 88;
    return ps;
}
void showlist(struct Student * pst)
{
    printf("%d %d\n",pst->sid,pst->age);
}
int main(void)
{
    struct Student * ps;
    ps = creatlist();
    showlist(ps);
    return 0;
}

运行结果:

相关推荐
在路上`27 分钟前
前端学习之后端java小白(四)之数据库设计
sql·学习
咔咔学姐kk3 小时前
大模型微调技术宝典:Transformer架构,从小白到专家
人工智能·深度学习·学习·算法·transformer
Jayyih3 小时前
嵌入式系统学习Day35(sqlite3数据库)
数据库·学习·sqlite
lingggggaaaa5 小时前
小迪安全v2023学习笔记(八十一讲)—— 框架安全&ThinkPHP&Laravel&Struts2&SpringBoot&CVE复现
笔记·学习·struts·安全·网络安全·laravel
papership5 小时前
【入门级-算法-6、排序算法: 插入排序】
数据结构·算法·排序算法
CC数分5 小时前
零基础3个月上岸[特殊字符]自学数据分析路线
学习·数据挖掘·数据分析·大学生·考证
HAH-HAH5 小时前
【蓝桥杯 2024 国 Java A】粉刷匠小蓝
c++·学习·数学·算法·职场和发展·蓝桥杯·组合数学
得意霄尽欢5 小时前
Redis之底层数据结构
数据结构·数据库·redis
酷讯网络_2408701606 小时前
多语言共享贩卖机投资理财共享售卖机投资理财系统
学习·开源
I'm a winner6 小时前
第五章:Python 数据结构:列表、元组与字典(二)
数据结构·python