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

运行结果:

相关推荐
GG不是gg10 分钟前
排序算法之高效排序:快速排序,归并排序,堆排序详解
数据结构·算法·排序算法
GG不是gg11 分钟前
排序算法之线性时间排序:计数排序,基数排序,桶排序详解
数据结构·算法·排序算法
qq_3863226914 分钟前
华为网路设备学习-22(路由器OSPF-LSA及特殊详解)
学习·华为·智能路由器
越城23 分钟前
深入理解二叉树:遍历、存储与算法实现
c语言·数据结构·算法
Hygge-star1 小时前
【数据结构】二分查找-LeftRightmost
java·数据结构·算法
oneDay++1 小时前
# IntelliJ IDEA企业版集成AI插件「通义灵码」全流程详解:从安装到实战
java·经验分享·学习·intellij-idea·学习方法
代码小将1 小时前
Leetcode76覆盖最小子串
笔记·学习·算法
z35026037061 小时前
dockers笔记
笔记
努力的小帅1 小时前
C++_STL_map与set
开发语言·数据结构·c++·学习·leetcode·刷题
田梓燊1 小时前
数学复习笔记 15
笔记·线性代数·机器学习