数组
#include<iostream>
using namespace std;
int main()
{
// 指针和数组
int arr[] = { 10,15,16,18,19 };
int* p = arr; // 根据之前知识,这里p指数组首地址
// 使用指针来遍历数组
for (int i = 0; i < 5; i++)
{
cout << *p << endl;
p++; // 相当于内存位置+1
}
system("pause");
return 0;
}
函数
#include<iostream>
using namespace std;
// 指针和函数
// 值传递:形参不影响实参,参考学习记录11
// 这里为地址传递,形参可以影响实参
void exchange(int* x1, int* x2)
{
int temp = *x1;
*x1 = *x2;
*x2 = temp;
}
// 即地址中的内容互换。
int main()
{
int a = 10;
int b = 20;
exchange(&a, &b);
cout << "a=" << a << endl;
cout << "b=" << b << endl;
system("pause");
return 0;
}
练习:封装一个函数,实现冒泡排序
#include<iostream>
using namespace std;
// 冒泡排序
void maopao(int* arr,int length) // 这里可以将数组理解为地址的集合,[]中的数字即为地址的索引
{
for (int i = 0; i < length-1; i++)
{
for (int j = 0; j < length - 1 - i; j++)
{
if (arr[j] >= arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void printarr(int* arr, int length)
{
for (int i = 0; i < length; i++)
{
cout << arr[i] << " ";
}
}
int main()
{
int arr[] = { 10,8,6,3,4,9,5,2,1,7 };
int length = size(arr);
maopao(arr, length);
printarr(arr, length);
system("pause");
return 0;
}