2019.09.30结构体概述与2019.10.10malloc()动态内存分配概述

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/KaiFcookie/article/details/102492933

2019.09.30

结构体
为什么会出现结构体:为了表示一些复杂的数据,而普通的基本类型变量无法满足要求
什么叫结构体:结构体是用户根据实际需要自己定义的复合数据类型
如何使用结构体:两种方式
struct Stdudent st ={1000,“zhangsan”, 20} ;
struct Stdudent * pst;

                1.st.sid
                2.pst->sid
                  pst所指向的结构体变量中的sid这个成员

注意事项:
结构体变量不能加减乘除 但可以相互赋值
普通结构体变量和结构体指针变量作为函数传参的问题

case1
#include <stdio.h>
struct Student
{
int sid;
char name [200];
int age;
};//分号不能省略
int main(void)
{
struct Student st={100,“zhangsan”",20};
printf("%d %s %d\n",st.sid,st.name,st.age);
st.sid=99;
//st.name=“lisi”;//error
strcpy(st.name,“lisi”);
st.age=22;
printf("%d %s %d\n",st.sid,st.name,st.age);
return 0;
}

or


int main (void)
{
struct Student st={1000,“zhangsan”,20);
//st.sid=99 //第一种方式
struct Student *pst;
pst=&st;
pst->sid=99; //pst->sid等价于(*pst).sid而(xpst).sid=st.sid

case2

#include <stdio.h>
#include <string.h>
struct Sudent
{
int sid;
char name[200];
int age;
};//分号不能省
void f(structural Student *pst);
void g(structural Student st);
void g2(structural Student *pst);
int main(void)
{
struct Student st;
f(&st);
g2(&st);
//printf("%d %s %d\n",st.sid,st.name,st.age);
return 0;
}
//这种方法耗内存 耗时间不提u见
void g(struct Student st)
{
printf("%d %s %d\n",st.sid,st.name,st.age);
}
void g2(struct Student *pst)
{
printf("%d %s %d\n",pst->sid,pst->name,pst->age);
}
void f(struct Student *pst);
{
(*pst)sid=99;
strcpy(pst->name,“zhangsan”);
pst->age=22;
}

_malloc()动态分配内存概述
动态内存的分配和释放
CASE 1
#icclude<stdio.h>
#include<malloc.h>
int main(void)
{
int a[5]={1,2,3,4,5}; //静态数组

int len;
printf(“请输入你需要分配的数组长度:len=”);
scanf(“%d”,&len);
int *pArr=(int *)malloc(sizeof(int)*len);	//(int *)为强制转换,强制使pArr指向前四个字节。可以将pArr当做数组名来操作
//*pArr=4;//类似于a[0]=4;

// pArr[1]=10;//类似于a[1]=10;
// printf(“%d %d\n”,pArr,pArr[1]);
//我们可以把pArr当做一个普通数组来使用
for (int i=0;i<len;++i)
scanf(“%d”,&pArr);
for (i=0;i<len;++i)
printf(“%d\n”,
(pArr+i));

free(pArr);	//把pArr所代表的的动态分配的20个字节的内存释放
return 0;

}

猜你喜欢

转载自blog.csdn.net/KaiFcookie/article/details/102492933
今日推荐