#include<iostream>
using namespace std;
//new 基本语法
int* create_new_int() {
// 在堆区创建整型数据
// new返回的是该类型的数据指针
int* p = new int(10);// 小空号 10 为值
return p;
}
int* create_new_int_array() {
// 在堆区创建整型数组
// new返回的整型数组的指针
int* arr = new int[10];// 中括号 10 意思为数组分配10个单位
// 赋值
for (int i = 0; i < 10; i++)
{
arr[i] = i + 1;
}
// 释放数组用 delete[]
//delete[] arr;
return arr;
}
int main() {
// new 整型
// 利用new创建堆区数据,用指针接函数返回的数据
int* p = create_new_int();
cout << p << endl;// 打印指针指向的内存位置
cout << p << endl;
cout << *p << endl;// 打印解引用的值 10
cout << *p << endl;
// 再用delete释放堆区数据
delete p;
// cout << *p << endl;//释放后打印会报错
// new 整型数组
int* arr_p = create_new_int_array();
// 访问
for (int i = 0; i < 10; i++)
{
cout << arr_p[i] <<",";
}
cout << endl;
system("pause");
return 0;
}
|