指针的作用
可以通过指针间接访问内存
内存编号是从0开始的,一般用十六进制数字表示
可以利用指针变量保存地址,
指针就是保存一个地址,是内存地址
#include<iostream>
using namespace std;
int main()
{
// 1. 定义指针
int a = 10;
// 指针定义的语法: 数据类型 * 指针变量名称
int *p;
// 让指针p 指向 a 的地址
p = &a;
cout << "a 的地址为" << &a << endl;
cout << "a 的地址转换成10进制" << int(&a) << endl;
cout << "指针p 的地址为" << p << endl;
// 2. 使用指针
// 可以通过解引用的方式来找到指针指向的内存
// 指针前加 * 代表解引用, 找到指针指向内存的数据
*p = 1000;
cout << "*p = " << *p << endl;
cout << "a = " << a << endl;
system("pause");
return 0;
}
指针所占内存空间
在32为操作系统下,占用4个字节, 64 位占8个字节
#include<iostream>
using namespace std;
int main()
{
int a = 20;
// int *p;
// p = &a;
// 下面是简便写法
int *p = &a;
// 在32 位操作系统下,指针是占4个字节大小,不管是什么类型的数据
cout << "sizeof(int *) = " << sizeof(p) << endl;
cout << "sizeof(int *) = " << sizeof(int *) << endl;
cout << "sizeof double = " << sizeof(double *) << endl;
cout << "sizeof char = " << sizeof(char *) << endl;
system("pause");
return 0;
}
空指针 和 野指针
空指针:指针变量指向内存中编号为0的空间
用途:初始化指针变量
注意:空指针指向的内存是不可以访问的
#include<iostream>
using namespace std;
int main()
{
// 空指针
// 1. 空指针用于给指针变量进行初始化
int *p = NULL;
// 2. 空指针是不可以进行访问的
// 0 - 255 之间的内存编号是系统占用的,因此不可以访问
system("pause");
return 0;
}
野指针:指针变量指向非法的内存空间
#include<iostream>
using namespace std;
int main()
{
// 野指针
// 在程序中,尽量避免出现野指针
int *p = (int *)0x100;
// 访问野指针报错
//cout << *p << endl;
system("pause");
return 0;
}
const 修饰指针
const 修饰指针有三种情况
- const 修饰指针 – 常量指针
- const 修饰常量 – 指针常量
- const 既修饰指针,有修饰常量
#include<iostream>
#include<string>
using namespace std;
int main()
{
int a = 10;
int b = 10;
// 1. const 修饰指针 常量指针
// 特点: 指针的指向可以修改,但是指针指向的值不可以修改
const int * p = &a;
// *p = 20; 错误, 因为指针指向的值不可以修改
p = &b; // 正确
//2. 指针常量 因为const 修饰的是常量
// 特点: 指针指向的值可以修改,指针的指向不可以改
int * const p2 = &a;
*p2 = 20; // 正确
// p2 = &b; 错误, 因为指针的指向不可以改
//3. const 既修饰指针,又修饰常量
const int * const p3 = &a;
// 特点: 指针的指向,指针指向的值都不可以修改
// p3 = &b; 错误
// *p3 = 20; 错误
system("pause");
return 0;
}
指针和数组配合使用
#include<iostream>
#include<string>
using namespace std;
int main()
{
// 指针和数组
// 利用指针访问数组中的元素
int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
cout << "第一个元素" << arr[0] << endl;
int *p = arr; // arr 就是数组的首地址
cout << "利用指针访问第一个元素" << *p << endl;
p++; // 让指针向后偏移4个字节
cout << "利用指针访问第二个元素" << *p << endl;
cout << "利用指针遍历数组" << endl;
int *p1 = arr;
for (int i = 0; i < sizeof arr / sizeof arr[0]; i++)
{
cout << "数组的第" << i << "个元素" << *p1 << endl;
p1++;
}
system("pause");
return 0;
}
指针和函数
#include<iostream>
#include<string>
using namespace std;
// 实现两个数字进行交换
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
// 放在这里可以交换
cout << "swap a = " << a << "swap b = " << b << endl;
}
void swap2(int *p1, int *p2)
{
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
int main()
{
// 指针和函数
// 1. 值传递
// int a = 10;
// int b = 20;
// swap(a, b);
// cout << "swap a = " << a << "swap b = " << b; 放在这里并不能交换
// 2. 地址传递
int a = 100;
int b = 200;
// 如果是地址传递,可以修饰实参
swap2(&a, &b);
cout << "swap2 a=" << a << "swap2 b = " << b << endl;
system("pause");
return 0;
}