指针
文章目录
- 指针
- 普通指针
- 基本使用
- new与delete
- 注意事项
普通指针
基本使用
//指针p指向t
int t = 123;
int*p = &t;
//C++11以上可用auto
auto pp = &t;
指针的大小为固定
int x = 5;
double y = 100;
int *px = &x;
double *py = &y;
char z = 'z';
char *pz = &z;
cout << sizeof(px) << endl;
cout << sizeof(py) << endl;
cout << sizeof(pz) << endl;
// 均为8
因此将指针自增加时会根据指向的内容进行自增
int a[5] = {1,2,3,4,5};
int *p = a;
for(int i = 0 ; i < 5 ; i ++ , p ++){
cout << *p << " ";
}
//1 2 3 4 5
new与delete
new用于动态申请存储空间,它比malloc更好
delete用于释放new申请的空间
- new与delete基本使用
int *x = new int(10);//申请了一个初值为10的整型数据
int *y = new int;
cout << *x << " " << *y << endl;
delete(x); delete(y);
- 数组使用
int *arr = new int[5];
for(int i = 0 ; i < 5 ; i ++)cout << arr[i] << " ";
delete []arr;//注意数组的delete
- 对类使用
class A{
public:
A(int t){
this -> x = t;
}
int getx(){
return this->x;
}
private:
int x;
};
int main() {
A* ptr = new A(5);
cout << ptr->getx() << endl;
}
注意事项
1.new与delete必须成对使用,delete会释放指针指向的内存但不会删除指针本身
int* ptr = new int(5);
delete ptr;
ptr = new int(6);
cout << *ptr << endl;
delete ptr;
//6
2.不要尝试释放已经释放的内存,delete只能释放new申请的内存
int* ptr = new int(5);
delete ptr;
delete ptr; //不行
int x = 6;
int* p = &x;
delete p; //不行