指针
指针的作用:可以通过指针间接访问内存
内存编号是从0开始记录的,一般用16进制数字表示
可以通过指针变量保存地址
定义指针与指针所占地址空间
int a = 10;
//定义指针
int * p;
//让指针记录变量a的地址
p = &a;
//指针前加*表示解引用,找到指向的数据
cout << "*p为" << *p << endl;
//&表示取地址
cout << "a的地址为" << &a << endl;
cout << "p地址为" << &p << endl;
cout << "p为" << p << endl;
指针所占空间
int a = 10;
int* p = &a;
cout << "sizeof(int *)=" << sizeof(int*) << endl;
cout << "sizeof(int *)=" << sizeof(float*) << endl;
cout << "sizeof(int *)=" << sizeof(double*) << endl;
cout << "sizeof(int *)=" << sizeof(char*) << endl;
//在32位操作系统下,指针占4个字节,64位操作系统为8个字节
空指针:指针变量指向内存编号为0的空间
用途:初始化指针变量
空指针指向的内存不可访问
int* p = NULL;
*p = 100;//会报错
野指针
int * p =(int *) 0x1100;
cout << *p << endl;//会报错,在程序中应尽量避免野指针
const修饰指针
注意看const后面紧跟的是哪个就是哪个不能变
const修饰指针2.const修饰变量3.const即修饰指针又修饰变量
常量指针:指针的指向可以修改,但是指针指向的值不可以修改
int a=10;int b=20;int *p=&a;
const int *p=&a;
//例:p指向A,&A=p;A=10;若令*p=20;不可以修改
//p=&b;指针重新指向另外一个变量,可以√
指针常量
int *const p=&a;
//特点:指向的值可以改,指针指向不可以改
const即修饰指针又修饰变量
int a = 10;
const int* const p = &a;
//特点:指针的指向和指向的值都不可以改
指针和数组
int arr[] = { 1,2,3,4,5,6,7,8,9,0 };
int* p = arr;
for (int i = 0; i < 10; i++)
{
cout << *p << endl;
p++;
}
指针与函数
创建函数
此处函数为下列所调用的函数
void swap01(int a, int b)
{
int temp = 1;
a = b;
b = temp;//交换函数
}
void swap02(int* p1, int* p2)
{
int tempp = *p1;
*p1 = *p2;
*p2 = tempp;//指针型交换函数
}
void bubbleSort(int* arr, int len)
{
for (int i = 0; i < len - 1; i++)
{
for (int j = 0; j < len - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void printArry(int* arr, int len)//打印数组
{
for (int i = 0; i < len; i++)
{
cout << arr[i] << endl;
}
}
调用函数
int a = 10;
int b = 20;
//swap01(a, b);
swap02(&a, &b);
cout << a << endl;
cout << b << endl;//与值的传递不同,地址的传递会改变实参
指针数组函数
封装一个函数,利用冒泡排序,实现对整数数组的升序排列
先创建一个数组
int arr[10] = { 4,3,6,9,1,2,10,8,7,5 };
int len = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr,len);
printArry(arr, len);