eg1:打印数组
// chapter10a03数组和指针案例.cpp
#include "pch.h"
#include <iostream>
using namespace std;
int main()
{
int arrays[] = { 2,4,6,8,10 };
int len = sizeof(arrays) / sizeof(arrays[0]);
// cout << len << endl;
int* ptr_arrays = arrays;
/*
//移动指针,打印数组
for (int i = 0; i < len; i++)
{
cout << *ptr_arrays++ << '\t';
}
cout << endl;
// 2 4 6 8 10
*/
//
for (int i = 0; i < len; i++)
{
cout << *(ptr_arrays + i) << '\t';
}
cout << endl;
}
eg2:打印数组并逆序打印
#include "pch.h"
#include <iostream>
using namespace std;
int main()
{
//数组逆序
int array1[] = { 1,3,5,7,9 };
int len1 = sizeof(array1) / sizeof(array1[0]);
int* ptr_array1_start = array1; //指向第一个元素
int* ptr_array1_end = array1 + 4; //指向最后一个元素
int temp;
cout << "正序打印:";
for (int i = 0; i < len1; i++)
{
cout << *(ptr_array1_start + i) << '\t';;
}
cout << endl;
while (ptr_array1_start != ptr_array1_end)
{
temp = *ptr_array1_start;
*ptr_array1_start = *ptr_array1_end;
*ptr_array1_end = temp;
ptr_array1_start++;
ptr_array1_end--;
}
cout << "逆序打印:";
for (int i = 0; i < len1; i++)
{
cout << array1[i] << '\t';
}
}
eg3:二维数组
// chapter10a04二维数组和指针.cpp
#include "pch.h"
#include <iostream>
using namespace std;
int main()
{
//用指针创建一维数组
int* p = new int[5];
p[0] = 5;
p[1] = 10;
p[2] = 15;
p[3] = 20;
p[4] = 25;
cout << "打印一维指针";
for (int i = 0; i < 5; i++)
{
cout << *(p +i) << ',';
}
cout << endl;
//用指针创建二维数组
int (*p2)[3] = new int[5][3]; //二维数组降维表示
p2[0][2] = 100;
p2[1][2] = 100;
p2[2][2] = 100;
p2[3][2] = 100;
p2[4][2] = 100;
cout << "打印二维指针" << endl;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
cout << p2[i][j] << ',';
//cout << *(*(p2 + i)+ j)
}
cout << endl;
}
}