结构体,链表,内存管理,union

1.结构体

声明一个结构体类型的一般形式为:

             struct    结构体名   {成员表列};

定义结构体类型变量:

(1)先声明结构体类型再定义变量名

例如:struct  student        student1, student2;

 

(2)在声明类型的同时定义变量

   这种般形式为:

      struct 结构体名

     {

         成员表列;

      }变量名表列;

 

实例:

#include <stdio.h>

struct student
{
    int name[20];
    int age;
    char man;
    char sex;
    short c;
    char s;
};

int main()
{
    struct student C1 = {"wdd", 21, 'm'};
    struct student C2; 

    scanf("%s%d %c", C2.name, &C2.age, &C2.sex);
    
    printf("%s %d %c\n", C1.name, C1.age, C1.sex);
    printf("%s %d %c\n", C2.name, C2.age, C2.sex);
    printf("%d\n",sizeof(struct student));
    return 0;
}

求结构体总长度的方法:1.结构体的总长度一定是最长成员的整数倍(double除外);

   2.每个成员的偏移量,一定是该成员长度的整数倍。

2.结构体数组:

 

struct student

{

int num;char name[20];

         char sex;int age;

float score;

char addr[30];

 }  stu[3];

定义了一个数组stu,数组有3个元素,均为struct student类型数据。

stu[3]也可以在函数里定义:struct student stu[3];

结构体指针数组:

#include<stdio.h>
#include<stdlib.h>
struct student
{
	char name[20];
	int age;
	char sex;
};
int main()
{
	int i;
	struct student *stu[5];
	for(i=0;i<5;i++)
	{
		stu[i]=(struct student*)malloc(sizeof(struct student));
		scanf("%s%d %c",stu[i]->name,&stu[i]->age,&stu[i]->sex);
	}
	for(i=0;i<5;i++)
	{
		printf("%s%d %c",stu[i]->name,stu[i]->age,stu[i]->sex);
	}
	return 0;
}

3.结构体和链表

用结构体建立链表:

struct student

{

          int num;

float score;

         struct student *next ;

};

  其中成员num和score用来存放结点中的有用数据(用户需要用到的数据),next是指针类型的成员,它指向struct student类型数据(这就是next所在的结构体类型)

即把一个结构体元素拆成两个部分,一个部分存放数据,另一个数据存放下一个元素的地址。

5.内存管理

在系统中启动一个进程时,系统会分配4g虚拟内存:

1g内存态

      3

    G

    用

    户

    态

用户态分为:数据段:全局变量、static静态变量(BBS、数据段)

   代码段:代码、常量(只读的)

   栈:局部变量(包括形参)

  堆空间:malloc、free

堆和栈区别:

栈:操作系统管理,申请释放都是操作系统完成

堆:用户管理,申请和释放由用户完成 ,申请:malloc      释放:free

实例:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int global = 0;//在数据段
char *p1; //在数据段
int main()
{
	int a;//在 栈空间
	char s[] = "abcd";//在 栈空间
	char *p2;//在 栈空间
	char *p3 = "1234567";//在 栈空间里一个指针变量指向一个在代码段的字符串量。
	static int c = 0;
	p1 = (char*)malloc(100); //在堆空间 分配了100字节 给p1.
	strcpy(p1,"123456789");//在 代码段里的字符串常量给了堆空间里的p1.
	return 0;
} 

6.联合体: union

union test //所有成员共享同一段内存(只为最长字节成员分配空间)

{

    char a;

    int b;

    long c;

};//只为 int /long 分配4个字节。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值