1:new运算符操作
#include<iostream>
using namespace std;
int* func()
{
//堆区创建整型数据
//new返回是 该数据类型的指针
int* p = new int(10);
return p;
}
void test01()
{
int* p = func();
cout << *p << endl;
cout << *p << endl;
cout << *p << endl;
cout << *p << endl;
//堆区的数据有程序员管理开辟和释放
//利用关键字delete
delete p;
//cout << *p << endl;
}
void test02(){
int* arr = new int[10];
for (int i = 0; i < 10; i++) {
arr[i] = i + 100;
}
for (int i = 0; i < 10; i++ ) {
cout << arr[i] << endl;
}
delete[] arr;
}
int main() {
test01();
test02();
system("pause");
}``
2:堆区:
```cpp
#include<iostream>
using namespace std;
int* func()
{
//int a = 10;
//利用new关键字,可以将数据开辟到堆区
//指针,本质也是局部变量,放在栈上,指针保存的数据时放在堆区
int* p = new int(10);
return p;
}
int main() {
int* p = func();
cout << *p << endl;
cout << *p << endl;
system("pause");
return 0;
}
3:全局区:
#include <iostream>
using namespace std;
//全局变量
int m_a = 0;
int main() {
//局部变量
int a = 0;
cout << "全局变量a的地址为 : " << (int)&a<<endl;
//静态变量
static int s_a = 0;
//字符串常量
cout << "Hellowork" << endl;
system("pause");
return 0;
}
4:栈区
#include<iostream>
using namespace std;
int* func()
{
int a = 10;
return &a;//不要返回局部变量的地址,栈区开辟的数九由编译器自动释放
}
int main() {
int* p = func();
cout << *p << endl;//第一次输出正确时因为编译器作了保留,第二次就会出错
cout << *p << endl;
system("pause");
return 0;
}