指针基础用法
#include<iostream>
using namespace std;
void swap01(int* p1, int* p2);
int main()
{
int a = 10;
int * p;
p = &a;
cout << &a << endl;
cout <<p<< endl;
//*p 解引用 找到指针指向的内存中的数据
*p = 100;
cout << a << endl;
cout << *p << endl;
cout << sizeof(p) << endl;
//空指针 用来初始化 不能访问
int* p1 = NULL;//NULL 代表0
//*p1 = 100;//错误用法 不能访问 没有权限
//0-255编号是系统占用的 因此不能访问
//野指针
//int* p2 = (int*)0x1011;
//cout<<*p2<<endl;//访问野指针报错 没有权限
//const 修饰指针 常量指针 指针的指向可以修改 但是指针指向的值不可以修改
int a1 = 10;
int b1 = 10;
const int* p3 = &a1;
p3 = &b1;
//*p3 = 100;//不可修改
//const 修饰常量 指针常量 指针的指向不可修改 指针指向的值可以修改
int a2 = 10;
int b2 = 10;
int* const p4 = &a2;
//p4 = &a2;//指针的指向不可修改
*p4 = 100;
//const 修饰指针也修饰常量 常量指针和指针常量 指针指向不可修改 指针指向的值也不可以修改
int a3 = 10;
int b3 = 20;
const int* const p5 = &a3;
//p5 = &b3;//指针指向不可修改
//*p5 = 100;//指针指向的值也不可修改
//指针访问数组
int arr[] = { 0,1,2,3,4,5,6,7,8,9 };
int* p6 = arr;
for (int i = 0;i < sizeof(arr)/sizeof(arr[0]);i++)
{
cout << *p6 << endl;
p6++;
}
//函数调用 地址传递
int a4 = 10;
int b4 = 20;
swap01(&a4, &b4);
cout << a4 << endl;
cout << b4 << endl;
return 0;
}
void swap01(int* p1, int* p2)
{
int t = *p1;
*p1 = *p2;
*p2 = t;
}
没有评论:
发表评论