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

运行结果:

相关推荐
小张的博客之旅2 小时前
2025年“羊城杯”网络安全大赛 线上初赛 (WriteUp)
python·学习·网络安全
周杰伦_Jay2 小时前
【Java集合体系】全面解析:架构、原理与实战选型
java·开发语言·数据结构·链表·架构
~无忧花开~3 小时前
JavaScript学习笔记(二十八):JavaScript性能优化全攻略
开发语言·前端·javascript·笔记·学习·性能优化·js
机器学习之心3 小时前
PINN物理信息神经网络风电功率预测!引入物理先验知识嵌入学习的风电功率预测新范式!Matlab实现
神经网络·学习·matlab·风电功率预测·物理信息神经网络
tkevinjd3 小时前
反转链表及其应用(力扣2130)
数据结构·leetcode·链表
HalvmånEver3 小时前
红黑树实现与原理剖析(上篇):核心规则与插入平衡逻辑
数据结构·c++·学习·算法·红黑树
BreezeJuvenile4 小时前
外设模块学习(5)——DS18B20温度传感器(STM32)
stm32·嵌入式硬件·学习·温度传感器·ds18b20
cimeo4 小时前
【C学习】13-数组使用与运算
学习·c#
yanqiaofanhua5 小时前
C语言自学--预处理详解
c语言·开发语言
一只小风华~5 小时前
学习笔记:Vue Router 中的链接匹配机制与样式控制
前端·javascript·vue.js·笔记·学习·ecmascript