结构体 动态内存的分配和释放
- 为什么会出现结构体
- 为了表达一些复杂的数据,而普通的基本类型变量无法满足要求
- 什么叫结构体
- 结构体是用户根据实际需要自己定义的复合数据类型
- 如何使用结构体
- 两种方式:
- struct Student st = {1000,”zhangsan”, 20};
- struct Student * pst = &st;
- 1.st.sid
- 2.pst->sid
pst所指向的结构体变量中的sid这个成员
- 两种方式:
- 注意事项
- 结构体变量不能加减乘除,但能相互赋值
- 普通结构体变量和结构体指针变量作为函数传参的问题
结构体练习代码
#include<stdio.h>
#include<string.h>
struct Student {
int sid,age;
char name[256];
};
void f(struct Student *pst);
void g(struct Student *pst);
void h(struct Student st);
int main() {
struct Student st;
f(&st);
g(&st);
h(st);
printf("3.%d %s %d\n",st.sid,st.name,st.age);
}
void f(struct Student *pst){
(*pst).sid=99;
strcpy(pst->name,"lisi");
pst->age=22;
}
void g(struct Student *pst){
printf("1.%d %s %d\n",pst->sid,pst->name,pst->age);
}
void h(struct Student st){
printf("2.%d %s %d\n",st.sid,st.name,st.age);
}
动态内存的分配和释放:
- 动态构造一维数组
- 假设动态构造一个int型数组
- p=(int )malloc(int len);
- 1.malloc只有一个int型的形参,表示要求系统分配的字节数
- 2.malloc函数的功能是请求系统len个字节的内存空间,如果请求分配成功,则返回第一个字节的地址(俗称干地址)转化为一个有实际意义的地址,因此,malloc前面必须加(数据类型*),表示吧这个舞实际意义的第一个字节的地址,转化为响应的地址。如:
- int p=(int )malloc(50);
- 表示将系统分配好的50个字节的第一个字节的地址转化为int *型的地址,更准确的说是把第一个字节的地址转化为四个字节的地址,这样p就指向了第i+1个的4个字节。p[0]就是第一个元素,p[i]就是第i+1个元素
- int p=(int )malloc(50);
- 假设动态构造一个int型数组
#include<stdio.h>
#include<malloc.h>
int main(){
int a[5]={4,10,2,8,6};
int len;
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 ",pArr[i]);
free(pArr);
}
跨函数使用内存代码
代码1
#include<stdio.h>
#include<stdlib.h>
struct Student{
int sid;
int age;
};
struct Student * CreateStudent(void);
void ShowStudent(struct Student*pst);
int main() {
struct Student * ps;
ps = CreateStudent();
ShowStudent(ps);
}
struct Student * CreateStudent(void){
struct Student *p=(struct Student*)malloc(sizeof(struct Student));
p->sid=99;
p->age=88;
return p;
}
void ShowStudent(struct Student*pst){
printf("%d %d",pst->sid,pst->age);
}
代码2
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct node{
int data;
struct node *next;
};
struct node *CreateList(void){
struct node *pH=NULL;
int len;
int i;
int temp;//存放用户暂时存入的结点的值域的值
struct node *pNew=NULL;//存放临时分配好的结点本身的内容
struct node *pTail=NULL;
pH=(struct node *)malloc(sizeof(struct node));
if(NULL==pH){
puts("动态内存分配失败!");
exit(-1);
}
pH->next=NULL;
pTail=pH;
printf("请输入结点个数:len = ");
scanf("%d",&len);
for(i=0;i<len;i++){
printf("请输入第%d个结点的值:",i+1);
scanf("%d",&temp);
//临时构造一个结点
pNew=(struct node *)malloc(sizeof(struct node));
if(NULL==pNew)
exit(-1);
pNew->data=temp;
pNew->next=NULL;
pTail->next=pNew;
pTail=pNew;
}
return pH;
}
bool TraversList(struct node *pH){
struct node *p=pH->next;
while(NULL!=p){
printf("%d ",p->data);
p=p->next;
}
printf("\n");
return true;
}
int main() {
struct node *pH=NULL;
pH=CreateList();
TraversList(pH);
}