第六讲:c/c++复合数据类型struct以及联合类型union,动态内存申请malloc和calloc
2017-04-08 15:47
501 查看
本文的编写是为了在学习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来释放内存。
相关文章推荐
- C++中常见数据类型的sizeof值,以及计算struct和union的详细方法
- hive的三种复合数据类型array、map、struct以及自定义分割符示例
- 关于struct,union,enum三大复合数据类型
- Struct结构体是C/C++语言中用来自定义数据类型的
- C++自定义数据类型之联合
- 大端小端存储模式以及其对Union数据类型的影响
- 大端小端存储模式以及其对Union数据类型的影响
- 【WebService】CXF处理javaBean等复合类型以及Map等复杂类型的数据
- C++ bool,char,short,int,long,float,double数据类型大小以及数据溢出值求解
- C++中关于原始数据类型指针变量的new操作以及delete操作
- C++复合数据类型
- union联合 数据类型 详细说明
- c++ 学习笔记之复合数据类型
- 动态内存申请函数选择(realloc、malloc 、alloca、 calloc)
- C++:联合类型(union)
- 【WebService】CXF处理javaBean等复合类型以及Map等复杂类型的数据
- C++读写txt文件方式以及基于opencv的Mat数据类型读写txt文件类型
- C语言数据类型:联合(union)
- 动态内存申请函数选择(realloc、malloc 、alloca、 calloc)
- C/C++动态内存管理之calloc ,malloc,realloc的区别