动态内存的分配和释放
打个例子:
#include <stdio.h>
#include <malloc.h>
int main(void)
{
int a[5] = {10, 22, 2021, 2001, 2020};
int len;
printf("请输入需要分配的数组的长度:len = ");
scanf("%d",&len);
int * pArr = (int *)malloc(sizeof(int) * len);
int i;
// 可以将pArr当作一个普通数组来使用
for(i = 0; i < len; i++)
{
scanf("%d",&pArr[i]);
}
for(i = 0; i < len; i++)
{
printf("%d\t",*(pArr+i));
//等价于 printf("%d\t",pArr[i]);
}
free(pArr); //将pArr所代表的动态分配的4*len个字节的内存释放
return 0;
}
跨函数使用内存
#include<stdio.h>
#include<malloc.h>
struct Student
{
int sid;
int age;
};
// 函数申明
struct Student * CreateStudent(void);
void ShowStudent(struct Student * ps);
int main(void)
{
struct Student * ps;
ps = CreateStudent();
ShowStudent(ps);
return 0;
}
struct Student * CreateStudent(void)
{
struct Student * p = (struct Student *)malloc(sizeof(struct Student));
p->sid = 1001;
p->age = 21;
return p;
}
void ShowStudent(struct Student * pst)
{
printf("%d %d\n", pst->sid,pst->age);
}