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

相关推荐
仰泳的熊猫2 分钟前
题目1109:Hanoi双塔问题
数据结构·c++·算法·蓝桥杯
七夜zippoe3 分钟前
Cython终极性能优化指南:从Python到C++的混合编程实战
c++·python·macos·cython·类型系统·内存视图
优雅的潮叭9 小时前
c++ 学习笔记之 shared_ptr
c++·笔记·学习
SunkingYang9 小时前
QT中使用Lambda表达式作为槽函数用法,以及捕获列表和参数列表用法与区别
c++·qt·用法·lambda表达式·捕获列表·槽函数·参数列表
微露清风9 小时前
系统性学习C++-第二十二讲-C++11
java·c++·学习
代码村新手10 小时前
C++-类和对象(中)
java·开发语言·c++
Ccjf酷儿11 小时前
C++语言程序设计 (郑莉)第十章 泛型程序设计与C++标准模板库
开发语言·c++
明洞日记14 小时前
【CUDA手册002】CUDA 基础执行模型:写出第一个正确的 Kernel
c++·图像处理·算法·ai·图形渲染·gpu·cuda
oioihoii15 小时前
程序员如何系统入门Vibe Coding?
c++
C+++Python15 小时前
C++类型判断
开发语言·c++