动态和静态内存分配时机
静态内存分配
确定大小的,作用域内使用
静态时注意分析内存地址,如果共享空间后续内容会导致所有的内容一致
动态内存分配
不确定大小的,作用域为也可以使用
- 用户输入
- 数据库中的变长字段、文件
- 数据结构,如链表、队列中的指针类型
- 使用:
char*,String
示例
结合场景(用户输入)和内存地址分析,可以
- 选择动态分配
- 也可以选择使用数组而不是指针
- 也可以使用String而不是指针
静态
注意name是指针类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| #ifndef STUDENT_H #define STUDENT_H
class Student { public: Student();
Student(char *name, int age);
~Student();
void show() const;
int getAge();
void setAge(int age);
void setName(char *name);
private: char *name; int age; };
#endif
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| #include "student.h" #include <iostream> #include <string.h> using namespace std;
Student::Student() { } Student::Student(char *name, int age) { this->name = name; this->age = age; }
Student::~Student() { cout << "析构函数执行了" << endl; }
void Student::show() const { cout << "name--" << this->name << endl; cout << "age--" << age << endl; }
int Student::getAge() { return this->age; }
void Student::setAge(int age) { this->age = age; }
void Student::setName(char *name) { this->name = name; }
|
- 前三个会发现name都是第三次输入的name,原因:共享内存(就是那个name[20]的地址)
- 后两个正常,那两个name值有系统分配的独立地址(栈上)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| #include <iostream> #include <student.h> using namespace std;
int main() { Student *students = new Student[5];
for (int i = 0; i < 3; i++) { char name[20]; int age; cout << "请输入第" << i + 1 << "个学生的姓名、年龄:" << endl; cin >> name; cin >> age; students[i].setAge(age); students[i].setName(name); }
students[3].setName("zwh"); students[3].setAge(20);
students[4].setName("java"); students[4].setAge(21);
for (int i = 0; i < 5; i++) { students[i].show(); }
delete students; return 0; }
|
动态
student.h和main.cpp与前面的一样,student.cpp使用动态分配
- 发现都正常,每个的用户名都不同,原因,都有独立的内存地址(堆上)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| #include "student.h" #include <iostream> #include <string.h> using namespace std;
Student::Student() { } Student::Student(char *name, int age) { this->name = new char[strlen(name) + 1]; strcpy(this->name, name); }
Student::~Student() { cout << "析构函数执行了" << endl; delete[] name; name = NULL; }
void Student::show() const { cout << "name--" << this->name << endl; cout << "age--" << age << endl; }
int Student::getAge() { return this->age; }
void Student::setAge(int age) { this->age = age; }
void Student::setName(char *name) { this->name = new char[strlen(name) + 1]; strcpy(this->name, name); }
|