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

运行结果:

相关推荐
我是伪码农6 小时前
百蝶杯学习
学习
keyipatience7 小时前
JavaScript学习(1)书写位置,变量、数据类型、运算符
开发语言·前端·javascript·css·学习
hanlin037 小时前
刷题笔记:力扣第32题-最长有效括号
笔记·算法·leetcode
All for pursuit.7 小时前
【动态规划-21】312.戳气球
数据结构·c++·算法·leetcode·动态规划
xian_wwq8 小时前
【学习笔记】Milvus 如何完成一次向量相似度检索,Milvus 索引到底应该怎么选?-15
笔记·学习·milvus
Hhuhkt9 小时前
3D 云养宠小游戏
学习
Zwawa10 小时前
先把轮子转稳,才不会烧心:编码器速度环 PID 怎么接回 PWM
c语言·单片机·嵌入式
派大鑫wink10 小时前
纯前端实现软考中级·软件设计师备考学习网站
前端·学习
smartpi_ai11 小时前
51 单片机写好了,大模型语音怎么接?17T 全驱动的现成方案、双板串口分工的边界与画板前的三项硬件确认
单片机·嵌入式硬件·学习
YSL07012411 小时前
贪吃蛇小游戏---古法编程
数据结构·游戏程序