VS2017学习C++基础九(数组和指针的案例)

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

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值