指针的定义和使用

image-20220114214024786


指针所占内存和空指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
using namespace std;
int main()
{
int a = 10;
//方式一
//int*p;
//p = &a;
//方式二
int*p = &a;
//指针所占内存空间
//在32位操作系统下,指针大小都是4个字节,不论什么类型,64位则是8个字节
cout << "sizeof(int*)= " << sizeof(p)/*或者sizeof(int*)*/ << endl;
cout << "sizeof(double*)= " << sizeof(double*) << endl;
cout << "sizeof(char*)= " << sizeof(char*) << endl;
cout << "sizeof(float*)= " << sizeof(float*) << endl;

//空指针用于给指针变量初始化
int*p = NULL;
//空指针的内存是不可以访问的
//0-255是的内存编号系统内存,无权限访问
system("pause");
return 0;
}

指针与数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#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; //arr就是数组的首地址
cout << "利用指针访问第一个元素:" << *p << endl;

p++;//让指针向后偏移4个字节,因为一个int占四个字节,加一则加四个字节
cout << "利用指针访问第二个元素:" << *p << endl;
//利用指针访问数组中所有元素
for (; *p<10; p++)
{
cout << *p;
}
cout << endl;
//方式二
int *p2 = arr;
for (int i = 0; i < 10; i++)
{
cout << *p2;
p2++;
}
system("pause");
return 0;
}

const修饰指针

常量指针

1
2
3
4
5
6
7
8
9
#include<iostream>
using namespace std;
int main()
{
const int * p=&a;
/*常量指针
特点:指针的指向可以改变,但是指针的数值不可以改变*/

}

image-20220122001257970

指针常量

1
2
3
4
5
6
7
#include<iostream>
using namespace std;
int main()
{
int * const p = &a;
//特点:指针的指向不能改,指向的值可以改
}

既修饰指针又修饰常量

1
2
3
4
5
6
7
#include<iostream>
using namespace std;
int main()
{
const int * const * = &a;
//特点:指针指向和指针指向的值都不可以改
}

函数与指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>
using namespace std;
void swap(int* p1, int* p2)
{
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
int main()
{
//如果是地址传递,可以修饰实参
int a = 10, b = 20;
swap(&a, &b);
cout << "a= " << a << endl;
cout << "b= " << b << endl;
return 0;
}

image-20220122110943878


指针配合数组和函数案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#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++)
{
//如果j>j+1的值,实现交换
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,7,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;
}