C,C++——指针详解

目录

1.指针的基本概念

代码示例:

2.指针所占内存空间

代码示例:

3.空指针和野指针

代码示例:

4.const修饰指针

代码示例:

5.指针和数组

代码示例:

6.指针和函数

代码示例:

[7.指针,数组,函数 练习](#7.指针,数组,函数 练习)

代码示例:


1.指针的基本概念

代码示例:

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;

int main()
{
	int a = 10;
	
	int *p;
	
	p = &a;
	cout << &a << endl;
	cout << p << endl;
	
	cout << "*p = " << *p << endl;
	return 0;
}

2.指针所占内存空间

代码示例:

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;

int main()
{
	//在32位操作系统下,指针占4个字节空间大小,无论是什么数据类型
	//在64位操作系统下,指针占8个字节空间大小,无论是什么数据类型
	cout << sizeof(int *) << endl;
	cout << sizeof(double *) << endl;
	cout << sizeof(float *) << endl;
	cout << sizeof(char *) << endl;
	return 0;
}

3.空指针和野指针

代码示例:

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;

int main()
{
//空指针用于给指针变量初始化,并且空指针指向的内存不可以被访问
	int *p = NULL;
	*p = 100;
	
//在程序中,尽量避免出现野指针
	int *p1 = (int *)0x1100;
	cout << *p1 << endl;
	return 0;
}

4.const修饰指针

代码示例:

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;

int main()
{
	int a = 10;
	int b = 10;
	
	//第一种,常量指针
	const int *p1 = &a;
	//指针指向的值不可以修改,指针的指向可以修改
	//*p1 = 20//错误
	p1 = &b;//正确
	
	//第二种,指针常量
	int *const p2 = &a;
	//指针指向的值可以修改,指针的指向不能修改
	*p2 = 20;//正确
	//*p2 = &b//错误
	
	//第三种,const修饰指针和常量
	const int * const p3 = &a;
	//指针指向的值和指针的指向都不能修改
	//*p3 = 20;//错误
	//p3 = &b;//错误
	
	return 0;
}

5.指针和数组

代码示例:

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;

int main()
{
	int arr[] = {1,3,7,5,4,2,9,0};
	int *p = arr;
	cout << *p << endl;
	p++;
	cout << *p << endl;
	return 0;
}

6.指针和函数

代码示例:

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;

void swap(int *a,int *b)
{
	int temp = *a;
	*a = *b;
	*b = temp;
}

int main()
{
	int a = 10;
	int b = 20;
	cout << "交换前a的值为:" << a << endl;
	cout << "交换前b的值为:" << b << endl;
	
	swap(&a,&b);
	
	cout << "交换后a的值为:" << a << endl;
	cout << "交换后b的值为:" << b << endl;
}

7.指针,数组,函数 练习

代码示例:

cpp 复制代码
#include<bits/stdc++.h>
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;
			}
		}
	}
}

int main()
{
	int arr[10] = {5,6,3,2,9,1,0,7,4,9};
	
	int len = sizeof(arr)/sizeof(arr[0]);
	
	bubblesort(arr,len);
	
	for(int i = 0; i < 10; i++)
	{
		cout << arr[i] << ' ';
	}
	
	return 0;
}

相关推荐
add45a4 分钟前
C++中的原型模式
开发语言·c++·算法
2401_844221325 分钟前
C++类型推导(auto/decltype)
开发语言·c++·算法
2201_753877796 分钟前
高性能计算中的C++优化
开发语言·c++·算法
无限进步_6 分钟前
深入解析C++容器适配器:stack、queue与deque的实现与应用
linux·开发语言·c++·windows·git·github·visual studio
2501_945425156 分钟前
分布式系统容错设计
开发语言·c++·算法
2401_8845632414 分钟前
C++代码重构实战
开发语言·c++·算法
fpcc17 分钟前
跟我学C++中级篇—std::shared_ptr的线程安全性分析
开发语言·c++
2401_8319207428 分钟前
C++中的桥接模式
开发语言·c++·算法
m0_7434703730 分钟前
C++中的桥接模式变体
开发语言·c++·算法
gulinigar35 分钟前
C++中的观察者模式实战
开发语言·c++·算法