第六讲:c/c++复合数据类型struct以及联合类型union,动态内存申请malloc和calloc

来源:互联网 发布:51单片机串口通信协议 编辑:程序博客网 时间:2024/06/05 19:20
本文的编写是为了在学习c++的时候加深自己的记忆,同时也为与我一般的初学者提供一些参考,此处特别感谢微信公众号“c/c++的编程

教室”,我的学习过程按照公众号的推送进行学习的!

1.复合数据类型struct

(1)结构:结构其实就是将各种类型的关于某一个主体的信息糅合到一个结构类型当中,如:

伸缩型定义:

struct Student{
   char name[20];
   int  number;
};//注意分号

可以直接赋值定义: struct Student A={"Zhang San","15911111111"};

(2)简单程序应用

①定义变量A

#include "stdio.h"
#include "stdlib.h"
struct Student {
char name[20];
int  number;
};//注意此处分号不要丢了,结构声明以及定义
int main()
{
struct Student A;//结构A
printf("Please enter A's Name: \n");
gets_s(A.name);//"."运算操作,类似与"->"
printf("Please enter A's Number:\n");
scanf_s("%d", &A.number);
printf("A's Name is : %s\n", A.name);
printf("A's Number is : %d\n", A.number);
system("PAUSE");
return 0;
}

②定义指针*A

#include "stdio.h"
#include "stdlib.h"
struct Student {
char name[20];
int  number;
};
int main()
{
struct Student* A = (struct Student*)malloc(sizeof(struct Student));

//申请内存,为指针分配大小为sizeof(struct Student)的内存,同时将*A的类型定义为struct Student*型

//malloc是C/C++标准库函数,不过也只是在C里面使,C++的话有更好用的new和delete操作符

printf("Please enter A's Name: \n");
gets_s(A->name);
printf("Please enter A's Number:\n");
scanf_s("%d", &A->number);
printf("A's Name is : %s\n", A->name);
printf("A's Number is : %d\n", A->number);
free(A);//释放指针
system("PAUSE");
return 0;
}

2.联合类型union:联合就是联合使用内存,这是一种节省资源的方式

(1)联合类型:

union BookPhone{

        int   number;

        int   telphone;

        char   name[20];

};

(2)使用实例

#include <stdio.h>
#include <stdlib.h>
union BookPhone {
int number;
int telphone;
char name[20];
};
int main()
{
BookPhone A;
gets_s(A.name);
printf("%s\n", A.name);
A.number = 1;
printf("%s,%d\n", A.name, A.number);
A.telphone = 159111111;
printf("%s,%d,%d\n", A.name, A.number, A.telphone);
system("PAUSE");
return 0;
}

3.在这里提一下一个数据管理的动态内存申请:malloc和calloc

double * ptr;

ptr = (double*)malloc(50*sizeof(double));

这段代码请求 50 个 double 类型值的空间, 并且把 ptr 指向该空间的所在位置。

 malloc的参数就是我们想要的内存大小,为了不至于内存泄漏,为了不至于数组越界,所以我们就得更好的利用这个函数去动态分配内存。当然,在结束使用之后,记得使用free()将资源释放。free()参数就是要释放的内存,如果我们使用完ptr后,我们就用free将他释放掉:free(ptr)即可。和malloc一样,calloc也是动态分配内存的函数,该函数和malloc的用法有些不一样,如果我们用calloc来修改上面的定义就得这样写了:

double* ptr;

ptr = (double*)calloc(50,sizeof(double));

calloc同样可以用free来释放内存。






1 0
原创粉丝点击