一.动态分配
关键词为new和delete,这两个要同时存在。
1.用new申请基本类型结构:其保存在堆区
int *p = NULL;
p = new int;//申请一个基本类型的数据
*p = 100;
delete p;
//申请动态空间的同时 初始化空间
int *p1 = NULL;
p1 = new int(100);//申请一个基本类型的数据
delete p;
2.用new申请数组空间
int *arr = NULL;
arr = new int[5]{1,2,3,4,5};
delete [] arr;
二.字符串处理函数
以str开头的字符串处理的函数 默认遇到’\0’结束操作
需要头文件#include <string.h>
1.测量字符串的长度strlen
include <string.h>
char str[12] = "hello";
strlen(str);//返回数字,5
2.字符串拷贝函数strcpy
char dst[12] = "";
char src[] = "hello";
strcpy(dst,src);//dst的内容变为hello
strncpy(dst,src,2);//dst的内容为he
3.字符串追加函数strcat
char dst[12] = "hello";
char src[] = "world";
strcat(dst,src);//dst的内容变为helloworld
strncat(dst,src,2);//dst的内容为hellowo
4.字符串比较strcmp
char dst[] = "ab";
char src[] = "bc";
strcmp(dst,src);//返回1、-1或0,分别是大于、小于和等于
三.结构体
将不同类型的数组合成一个整体,关键词为struct
1.结构体基础
1.1 结构体的定义
struct Student
{
int num;
char name[20];
char sex;
}lucy;//lucy为定义的变量,也可以不定义
Student bob;//定义的变量
//一次性结构体类型
struct
{
int num;
char nane[20];
}lucy;
1.2 结构体变量的操作
结构体的初始化必须要遵循成员的顺序以及成员自身的数据类型
struct Student
{
int num;
char name[20];
};
Student lucy = {100,"lucy"};
cout<<lucy.num<<" "<<lucy.name<<endl;//100 lucy
1.3清空整个结构体变量
使用的memset
#include<string.h>
struct Student
{
int num;
char name[20];
};
Student lucy = {100,"lucy"};
memset(&lucy,0,sizeof(lucy));//0为清空后每个属性的值
1.4使用键盘给属性赋值
struct Student
{
int num;
char name[20];
};
Student lucy;
cout<<"输入数据";
cin>>lucy.num>>lucy.name;
单独赋值时要注意不能直接给数组赋值:
struct Student
{
int num;
char name[20];
};
Student lucy;
//lucy.name = "bob"这是错误的,因为name是常量名
strcpy(lucy.name,"aaa");
1.5相同结构体赋值
struct Student
{
int num;
char name[20];
};
Student lucy = {100,"lucy"};
Student bob;
//1.单个成员赋值
bob.num = lucy.num;
strcpy(bob.name,lucy.name);
//2.相同类型的结构体可以直接赋值
bob = lucy;
//3.内存的拷贝,为第2种的底层
memcpy(&bob,&lucy,sizeof(Student));
1.6结构体嵌套
struct Student
{
int num;
char name[20];
Date ob;
};
struct Date
{
int year;
int month;
int day;
}
cout<<lucy.ob.day;
2.结构体数组
2.1 结构体数组定义
struct Date
{
int year;
int month;
int day;
}
Student arr[5] = {{100,"lucy"},{101,"bob"},{102,"tom"},{103,"mm"},{104,"xiaobao"}};
//数组个数
int n = sizeof(arr)/sizeof(arr[0]);
3.结构体指针变量
3.1 结构体指针的定义
使用指针变量访问成员要用->
Student lucy = {100,"lucy"};
Student *p = &lucy;
cout<<(*p).num;
cout<<p->num;//地址采用->访问
cout<<(&lucy).num;
3.2 结构体的浅拷贝:
注意结构体中有存在指针变量是会存在一个空间多次释放的问题
原因是浅拷贝是将值直接拷贝,拷贝的构造变量中指针变量保存的是地址
3.3 结构体的深拷贝
可以拷贝有指针变量
struct Student
{
int num;
char *name;
};
Student lucy;
lucy.num = 100;
lucy.name = new char[32];
strcpy(lucy.name,"hello world");
Student bob;
bob.num = 100;
bob.name = new char[32];//给bob.name开辟空间就可以解决
strcpy(bob.name,lucy.name);
3.4 结构体为指针变量
注意当结构体中有指针成员时,要先释放成员,然后再释放结构体
Student *p = new Student;
p->name = new char[12];
//释放空间
delete [] p->name;
delete p;