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

运行结果:

相关推荐
梦帮科技5 小时前
AI 音乐产品的发布工程:验证门、数据发布、回滚与生产运维纪律
数据结构·数据库·架构·node.js·音视频·动态规划·推荐算法
一只路人甲6 小时前
使用AI快速学习
学习
C++ 老炮儿的技术栈6 小时前
我们在设计tcp协议时,要传一个字符串过去,报文:头十长度十内容,是否要把‘\0‘也填入,长度是否包含‘\0‘
开发语言·数据结构·c++·mfc·c
传奇开心果编程6 小时前
【Rust入门练中学】第2课:变量、可变性与常量
开发语言·学习·rust
Navigator_Z7 小时前
LeetCode //C - 1252. Cells with Odd Values in a Matrix
c语言·算法·leetcode
边境悍匪9 小时前
蜗牛学苑 Java 智能体学习 Day42|项目周开发技术汇总 1 思维导图复盘
java·开发语言·spring boot·学习·spring
Gyr09 小时前
浅刷了一遍51CTO软考题库客观题及其解析(4)
学习·软考·知识点·信息安全工程师
青山木9 小时前
Hot 100 --- 最长有效括号
java·数据结构·算法·leetcode·动态规划
是隼人9 小时前
buuctf-pwn [NewStarCTF 2023 公开赛道]stack migration(64位栈迁移)题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
ι:10 小时前
单相桥式全控整流仿真从零复现教学
windows·学习·matlab·simulink