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

运行结果:

相关推荐
好奇龙猫20 小时前
大学院-筆記試験練習:线性代数和数据结构(18)
数据结构·线性代数
测试_AI_一辰20 小时前
Agent & RAG 测试工程笔记 01:Tool Calling 跑通 + 本地 PDF 接入(智谱 GLM)
人工智能·笔记·功能测试·自动化·bug
观音山保我别报错20 小时前
SpringBoot 项目学习内容详解(二)
spring boot·后端·学习
QZ_orz_freedom20 小时前
后端学习笔记-Spring Task
笔记·学习
小酒丸子20 小时前
AD23绘制元件封装学习笔记
笔记·嵌入式硬件·学习
hit56实验室20 小时前
make -j时不知道cpu核数设置多大合适
笔记
week_泽20 小时前
随机森林样本权重的计算-弱学习器
学习·算法·随机森林
了一梨20 小时前
SQLite3学习笔记1:配置环境
笔记·学习·sqlite
新缸中之脑21 小时前
学习AI编程 vs. 学习编程
java·学习·ai编程
玄斎21 小时前
华为ENSP配置实验:双网段互通 + DNS 解析 + Web 访问,一步实现全网可达(基础)
运维·服务器·网络·学习·华为·hcia·ensp