学习目标:
1.掌握指针定义与用法
2.const修饰指针的三种情况
3.指针与数组
4.指针与函数
5.综合示例
学习内容:
1.掌握指针定义与用法
通过指针可以间接的访问内存;内存编号是从0开始的,一般用十六进制数字表示;可以利用指针变量保持地址
语法:数据类型 *指针变量名
例如:
int a = 18; //定义一个整型
int *p; //定义一个指针,其变量名为p
p = &a; //由于p是一个指针, 接收a的地址
2.const修饰指针的三种情况
- const 修饰指针(常量指针)
- const 修饰常量(指针常量)
- const既修饰指针,又修饰常量
const 修饰指针(常量指针)
常量指针:指针指向的值不能修改,指针的指向可以修改
int a = 10;
int b = 20;
const int *p = &a;//const修饰指针
*p = 20;//*p表示取值,先前为10,修改为20,数值发生变化,这种情况是错误的
p = &b;// p表示指针,表示指针的指向变化,这是允许的
const 修饰常量(指针常量)
指针常量:指针指向的值能修改,指针的指向不可以修改
int a = 10;
int b = 20;
int * const p = &a;//const修饰常量
*p = 20;//*p表示取值,先前为10,修改为20,数值发生变化,在指针常量中这种情况是允许的
p = &b;// p表示指针,表示指针的指向变化,不允许
const既修饰指针,又修饰常量
:指针的指向和指向的值都不能改变
3.指针与数组
通过地址偏移来表示指针
#include<iostream>
using namespace std;
int main()
{
int arr[6] = { 1, 2,3,4,5,6 };
int* p;
p = arr;//数组名表示首地址
cout << "利用指针访问第一个元素为:" << *p << endl;
p++;//让指针向后偏移4个字节
cout << "利用指针访问第二个元素为:" << *p << endl;
system("pause");
return 0;
}
通过指针来循环数组中所有的元素
#include<iostream>
using namespace std;
int main()
{
int arr[6] = { 1, 2,3,4,5,6 };
int* p;
p = arr;//数组名表示首地址
//for循环6次,表示要进行6次取值
for (int i = 0; i < 6; i++)
{
cout << *p << endl;
p++;//发生地址偏移
}
system("pause");
return 0;
}
4.指针与函数
利用指针作为函数的参数,可以改变实参
的值(地址传递)
#include<iostream>
using namespace std;
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
cout << "定义交换函数中数值情况为:" << endl;
cout << "a = " << *a << " b = " << *b << endl;
}
int main()
{
int a = 10;
int b = 20;
cout << "打印前主函数中的数值:"<<endl;
cout << "a = " << a << " b = " << b << endl;
cout << "****^^^^****" << endl;
swap(&a, &b);//传入相对应的地址,所以在定义函数时要定义指针来接收
cout << "****^^^^****" << endl;
cout << "打印后主函数中的数值:" << endl;
cout << "a = " << a << " b = " << b << endl;
system("pause");
return 0;
}
5.综合示例
案例描述:利用指针传值来完成冒泡排序,用两个分函数分别实现对应的功能:一个是排序,另一个是打印输出
#include<iostream>
using namespace std;
void BubbleSort(int* arr, int len);//将声明放在主函数前,那么函数体就可以放在主函数后面
void PrintSort(int* arr, int len);
int main()
{
int arr[6] = { 2,98,86,36,25,1 };
int len = sizeof(arr) / sizeof(int);
cout << "打印原有数组:" << endl;
for (int i = 0; i < len; i++)
{
cout << arr[i] << " ";
}
BubbleSort(arr, len);//数组名表示地址,传入地址要用指针接收
cout << endl;
PrintSort(arr,len);
cout << "打印排序后的数组:" << endl;
system("pause");
return 0;
}
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 PrintSort(int* arr, int len)
{
for (int i = 0; i < len; i++)
{
cout << *arr << " ";//通过地址偏移来完成打印输出
arr++;
}
}