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;
}

相关推荐
十五年专注C++开发29 分钟前
CMake基础:条件判断详解
c++·跨平台·cmake·自动化编译
QuantumStack3 小时前
【C++ 真题】P1104 生日
开发语言·c++·算法
天若有情6733 小时前
01_软件卓越之道:功能性与需求满足
c++·软件工程·软件
whoarethenext3 小时前
使用 C++/OpenCV 和 MFCC 构建双重认证智能门禁系统
开发语言·c++·opencv·mfcc
Jay_5154 小时前
C++多态与虚函数详解:从入门到精通
开发语言·c++
xiaolang_8616_wjl5 小时前
c++文字游戏_闯关打怪
开发语言·数据结构·c++·算法·c++20
small_wh1te_coder5 小时前
硬件嵌入式学习路线大总结(一):C语言与linux。内功心法——从入门到精通,彻底打通你的任督二脉!
linux·c语言·汇编·嵌入式硬件·算法·c
FrostedLotus·霜莲6 小时前
C++主流编辑器特点比较
开发语言·c++·编辑器
liulilittle10 小时前
深度剖析:OPENPPP2 libtcpip 实现原理与架构设计
开发语言·网络·c++·tcp/ip·智能路由器·tcp·通信
十年编程老舅11 小时前
跨越十年的C++演进:C++20新特性全解析
c++·c++11·c++20·c++14·c++23·c++17·c++新特性