结构体和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;
}

运行结果:

相关推荐
三品吉他手会点灯1 小时前
C语言学习笔记 - 1.C概述 - 本讲内容概述
c语言·笔记·学习
嵌入式小企鹅1 小时前
国产大模型与芯片加速融合,RISC-V生态多点开花,AI编程工具迈入自动化新纪元
人工智能·学习·ai·嵌入式·算力·risc-v·半导体
光影少年1 小时前
Monorepo架构是什么,如何学习Monorepo架构?
前端·学习·架构·前端框架
醇氧1 小时前
Hermes Agent 学习(安装部署详细教程)
人工智能·python·学习·阿里云·ai·云计算
码完就睡2 小时前
数据结构——栈和队列的相互模拟
数据结构
iiiiyu2 小时前
常用API(SimpleDateFormat类 & Calendar类 & JDK8日期 时间 日期时间 & JDK8日期(时区) )
java·大数据·开发语言·数据结构·编程语言
故事和你912 小时前
洛谷-数据结构1-4-图的基本应用2
开发语言·数据结构·算法·深度优先·动态规划·图论
是孑然呀2 小时前
【笔记】激光定位-激光切割指针偏移设置
笔记
光影少年3 小时前
Python+LangGraph学习路线及发展前景
开发语言·人工智能·python·学习
星辰即远方3 小时前
UI学习3
学习·ui