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

相关推荐
七七七七074 分钟前
C++类对象多态基础语法【超详细】
开发语言·c++
真的想上岸啊1 小时前
学习C++、QT---21(QT中QFile库的QFile读取文件、写入文件的讲解)
c++·qt·学习
小庞在加油1 小时前
Apollo源码架构解析---附C++代码设计示例
开发语言·c++·架构·自动驾驶·apollo
我喜欢就喜欢2 小时前
RapidFuzz-CPP:高效字符串相似度计算的C++利器
开发语言·c++
千帐灯无此声2 小时前
Linux 测开:日志分析 + 定位 Bug
linux·c语言·c++·bug
莫彩2 小时前
【Modern C++ Part7】_创建对象时使用()和{}的区别
开发语言·c++
科大饭桶4 小时前
数据结构自学Day5--链表知识总结
数据结构·算法·leetcode·链表·c
mit6.8244 小时前
[Meetily后端框架] Whisper转录服务器 | 后端服务管理脚本
c++·人工智能·后端·python
L_autinue_Star6 小时前
手写vector容器:C++模板实战指南(从0到1掌握泛型编程)
java·c语言·开发语言·c++·学习·stl
无小道8 小时前
c++--typedef和#define的用法及区别
c语言·开发语言·汇编·c++