C++基础入门---7.指针【P56~P63】
7. 指针
指针的作用:可以通过指针间接访问内存
- 内存编号是从0开始记录的,一般用16进制数字表示
- 可以利用指针变量保存地址
7.1 指针的定义和使用
# include<iostream>
using namespace std;
int main()
{
//1、定义指针
int a = 10;
//指针定义的用法:数据类型 * 指针变量名
int * p;
//让指针记录变量a的地址
p = &a;
cout << "a的地址为: " << &a << endl;
cout << "指针p为: " << p << endl;
//2、使用指针
//可以通过解引用的方式来找到指针指向的内存
//指针前加* 代表解引用,找到指针指向的内存中的数据
*p = 1000;
cout << "a= " << a << endl;
system("pause");
return 0;
}
7.2 指针所占内存空间
提问:指针也是种数据类型,那么这种数据类型占据多少内存空间?
回答:在32位(x86)操作系统下占用4个字节空间 ;在64为操作系统下,占用8个字节。
# include<iostream>
using namespace std;
int main()
{
int a = 10;
int * p = &a;
cout << "sizeof(int *)= " << sizeof(p) << endl;
system("pause");
return 0;
}
7.3 空指针
定义:指针变量指向内存中编号为零的空间;
用途:初始化指针变量;
注意:空指针指向的内存不可以访问。
# include<iostream>
using namespace std;
int main()
{
// 空指针
//1、空指针用于给指针变量进行初始化
int * p = NULL;
//2、空指针是不可以进行访问的
//0~255之间的内存编号是系统占用的,因此不可以访问
cout << *p << endl;
system("pause");
return 0;
}
7.4 野指针
野指针:指针变量指向非法的内存空间。
在程序中,应该精良避免野指针。
# include<iostream>
using namespace std;
int main()
{
// 野指针
int *p = (int *)0x1100;
cout << *p << endl;
system("pause");
return 0;
}
}
7.5 const修饰指针
# include<iostream>
using namespace std;
int main()
{
//1、const修饰指针 常量指针
int a = 10;
int b = 10;
const int * p = &a;
//指针指向的值不可以改,指针的指向可以改
//*p = 20;错误
p = &b;//正确
//2、const修饰常量 指针常量
//指针的指向不可以改,指针指向的值可以改
int * const p2 = &a;
*p2 = 100;//正确的
//p2=&b;//错误,指针的指向不可以改
//3、const修饰指针和常量
const int * const p3 = &a;
system("pause");
return 0;
}
7.6 指针和数组
作用:利用指针访问数组中的元素。
# include<iostream>
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;
cout << "利用指针访问数组第一个元素: " << *p << endl;
cout << "利用指针遍历数组" << endl;
for (int i = 0; i < 10; i++)
{
cout << *p << endl;
p++;
}
system("pause");
return 0;
}
7.7 指针和函数
作用:利用指针作函数参数,可以修改实参的值。
# include<iostream>
using namespace std;
void swap(int *p1, int *p2)
{
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
int main()
{
int a = 10;
int b = 20;
swap(&a, &b);
cout << a << endl;
cout << b << endl;
system("pause");
return 0;
}
7.8 指针配合数组和函数案例
# include<iostream>
using namespace std;
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 printArray(int *arr, int len)
{
for (int i = 0; i < len; i++)
{
cout << arr[i] << endl;
}
}
int main()
{
//1、先创建数组
int arr[10] = { 4,3,6,9,1,2,10,8,7,5 };
//数组长度
int len = sizeof(arr) / sizeof(arr[0]);
//2、创建函数,实现冒泡排序
bubbleSort(arr, len);
//3、打印数组
printArray(arr, len);
system("pause");
return 0;
}