首页 > 编程语言 >C++学习之指针进阶(转载)

C++学习之指针进阶(转载)

时间:2022-09-27 21:45:25浏览次数:45  
标签:arr 进阶 temp int C++ len 实参 指针

1 指针和数组

作用:利用指针访问数组中元素
示例:

int arr[] = { 1,2,3,4,5,6,7,8,9,10 };

int * p = arr;  //指向数组的指针

cout << "第一个元素: " << arr[0] << endl;
cout << "指针访问第一个元素: " << *p << endl;

for (int i = 0; i < 10; i++)
{
  //利用指针遍历数组
  cout << *p << endl;
  p++;
}

2 指针和函数

作用:利用指针作函数参数,可以修改实参的值
示例:

//值传递
void swap1(int a ,int b)
{
	int temp = a;
	a = b; 
	b = temp;
}
//地址传递
void swap2(int * p1, int *p2)
{
	int temp = *p1;
	*p1 = *p2;
	*p2 = temp;
}

int main() {

	int a = 10;
	int b = 20;
	swap1(a, b); // 值传递不会改变实参

	swap2(&a, &b); //地址传递会改变实参

	cout << "a = " << a << endl;

	cout << "b = " << b << endl;

	system("pause");

	return 0;
}

总结:如果不想修改实参,就用值传递,如果想修改实参,就用地址传递

3 指针、数组、函数

案例描述:封装一个函数,利用冒泡排序,实现对整型数组的升序排序

例如数组:int arr[10] = { 4,3,6,9,1,2,10,8,7,5 };

示例:

//冒泡排序函数
void bubbleSort(int * arr, int len)  //int * arr 也可以写为int arr[]
{
	for (int i = 0; i < len - 1; i++)
	{
		for (int j = 0; j < len - 1 - i; j++)
		{
			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() {

	int arr[10] = { 4,3,6,9,1,2,10,8,7,5 };
	int len = sizeof(arr) / sizeof(int);

	bubbleSort(arr, len);

	printArray(arr, len);

	system("pause");

	return 0;
}

总结:当数组名传入到函数作为参数时,被退化为指向首元素的指针

标签:arr,进阶,temp,int,C++,len,实参,指针
From: https://www.cnblogs.com/kylintao/p/16736097.html

相关文章

  • C++学习 Day9-01 指针-定义及使用
    指针变量定义语法:数据类型*变量名;示例:intmain(){ //1、指针的定义 inta=10;//定义整型变量a //指针定义语法:数据类型*变量名; int*p; //指针变量......
  • C++11 获取当前时间戳
    C++11标准库chrono中包含了获取系统当前时间的工具。直接基于chrono获取,一般获取ms级的时间戳#include<chrono>longlongget_cur_time(){//获取操作系统......
  • python进阶之路5
    作业讲解1.获取用户输入并打印成下列格式 ------------infoofJason-----------Name:JasonAge:18Sex:maleJob:Teacher-------......
  • [Oracle] LeetCode 88 Merge Sorted Array 双指针
    Youaregiventwointegerarraysnums1andnums2,sortedinnon-decreasingorder,andtwointegersmandn,representingthenumberofelementsinnums1andnu......
  • C++ string 性能测试
    1、使用“+=”性能对比代码如下#include<stdio.h>#include<stdlib.h>#include<iostream>#include<string>#include<time.h>usingnamespacestd;intmain(......
  • 【C++】之前学习C++没有注意到的点或者学到了冷知识(待补充)
    1.string和c_str()stringstr="hello";constchar*cstr=str.c_str();str="yep,im";本来是以为str.c_str()会把str中包含的字符串在内存中开辟一个新空间存放......
  • malloc与指针
    1错误写法#include<stdio.h>#include<stdlib.h>#defineMaxSize10//定义最大长度typedefstruct{intdata[10];//用静态的“数组”存放数据元素......
  • C++模板的哲学
    2.5模板C++的模板一直是这门语言的一种特殊的艺术,模板甚至可以独立作为一门新的语言来进行使用。模板的哲学在于将一切能够在编译期处理的问题丢到编译期进行处理,仅在运......
  • 前端面试总结06-异步进阶
    1.事件循环(1:JS是单线程运行的(2:异步要基于回调来实现(3:eventloop就是异步回调的实现原理2.JS如何执行从前到后一行一行执行如果某一行执行报错,则停止下面代码的执行......
  • 学习笔记-C++ STL篇
    1、C++中vector作为参数的三种传参方式(传值&&传引用&&传指针)https://blog.csdn.net/weixin_47641702/article/details/113522865c++中常用的vector容器作为参数时,有......