07 指针
本次记录指针,还请各位大佬批评指正!
定义
//定义指针
int a = 10;
int * p;
p = &a;
//上边两行可以和写为 int* p = &a;
cout << "a的地址为" << &a << endl;
cout << "指针p为" << p << endl;
使用
指针前加 * 代表解引用,找到指针指向的内存中的数据
int * p;
* p = 1000;
cout << "*p=" << *p << endl;
指针所占内存空间
32位操作系统(x86),指针占4个字节;64位操作系统(x64),指针占8个字节;
int a = 10;
int* p = &a;
cout << "sizeof(int *)=" << sizeof(int *) << endl;
cout << "sizeof(float *)=" << sizeof(float *) << endl;
cout << "sizeof(double *)=" << sizeof(double *) << endl;
cout << "sizeof(char *)=" << sizeof(char *) << endl;
空指针和野指针
空指针和野指针都不是我们申请的空间,因此不要访问。
//空指针 0~255之间的内存编号是系统占用的,因此不可以进行访问
int * p = NULL;
//野指针 在程序中尽量避免野指针
int * p = (int*)0x1100;
cout << "*p=" << *p << endl;
const修饰指针
1、const修饰指针 常量指针;
2、const修饰常量 指针常量;
3、const既修饰指针,又修饰常量;
4、看const后边紧跟着的是指针还是常量,是指针就是常量指针,是常量就是指针常量。
//const修饰指针 常量指针 (指针的指向可以修改,但是指针的值不可以改)
int a = 10;
int b = 10;
const int * p = &a;
// *p = 20;//错误
p = &b; //正确
//const修饰常量 指针常量 (指针的指向不可以修改,但是指针的值可以改)
int a = 10;
int b = 10;
int *const p = &a;
*p = 20; //正确
//p = &b; //错误
//const既修饰指针,又修饰常量 (指针的指向和值都不可以修改)
int a = 10;
int b = 10;
const int* const p = &a;
//*p = 20; //错误
//p = &b; //错误
指针和数组
利用指针访问数组中的元素。
//指针和数组 利用指针访问数组中的元素
int arr[10] = {1, 2 ,3, 4, 5, 6, 7 ,8, 9, 10};
//cout << "第一个元素为:" << arr[0] << endl;
int * p = arr;//arr就是数组的首地址
//cout << "利用指针访问第一个元素为:" << *p << endl;
//cout << "利用指针访问第二个元素为:" << *++p << endl;//让指针向后偏移4个字节
for (int i = 0; i < 10; i++)
{
cout << "利用指针访问第"<< i+1 <<"个元素为:" << *(p + i) << endl;
}
指针和函数
1、值传递
#include<iostream>
#include<string>
#include<time.h>
using namespace std;
void swap01(int a, int b)
{
int temp = a;
a = b;
b = temp;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
}
int main()
{
//值传递 不改变实参
int a = 10;
int b = 20;
swap01(a, b);
cout << "a=" << a << endl;
cout << "b=" << b << endl;
system("pause");
return 0;
}
2、地址传递
#include<iostream>
#include<string>
#include<time.h>
using namespace std;
void swap02(int * p1, int * p2)
{
int temp = * p1;
* p1 = * p2;
* p2 = temp;
}
int main()
{
//地址传递 改变实参
int a = 10;
int b = 20;
swap02(&a, &b);
cout << "a=" << a << endl;
cout << "b=" << b << endl;
system("pause");
return 0;
}
指针、数组和函数
封装一个函数,利用冒泡排序,实现对整型数组的升序排序。例如数组:int arr[10] = { 4,3,6,9,1,2,10,8,7,5 };
#include<iostream>
#include<string>
#include<time.h>
using namespace std;
void bubblesort(int* arr, int len)//int *arr也可写为int arr[]
{
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 printarr(int* arr, int len)
{
for (int k = 0; k < len ; k++)
{
cout << arr[k] << endl;
}
}
int main()
{
int arr[10] = { 4,3,6,9,1,2,10,8,7,5 };
int len = sizeof(arr) / sizeof(arr[0]);
bubblesort(arr, len);
printarr(arr, len);
system("pause");
return 0;
}