ca29a_demo_c ++ pointers and arrays _ How to use pointers to access array

/ * 29_CppPrimer_ arrays and pointers
used to access an array of pointers
pointer arithmetic
dereferencing the pointer and the interaction between the arithmetic operations
subscripts and pointer
array for calculating the pointer beyond the end of
the output array element
pointer array iterators

*/

/*29_CppPrimer_指针和数组txwtech
使用指针访问数组
指针的算术操作
解引用和指针算术操作之间的相互作用
下标和指针
计算数组的超出末端指针
输出数组元素
指针是数组的迭代器

*/
#include <iostream>
#include <vector>
using namespace std;

int main()
{
	int ia[] = {9,2,4,6,8};
	int *ip = ia;

	cout << *ia << endl;
	cout << *ip << endl;

	ip = &ia[4];
	//ip=&ia[0];//同ip=ia;
	cout << *ip << endl;
	ip = ia;
	int *ip2 = ip + 4;//同 ip = &ia[4];//*ip2 = ia + 4;
	cout << *ip2 << endl;

	int *ip3 = ip + 10; //下标越界了,数据错误
	cout << *ip3 << endl;//下标越界了,数据错误

	ptrdiff_t n = ip2 - ip;//数据元素间隔几个数据,n=4
	cout << n << endl;
	
	int last = *ia;//对指针进行解引用
	cout << "last: "<<last << endl;

	int last1 = *ia+4;//先解引用,再加4,9+4=13
	cout << last1 << endl;

	int last2 = *(ia + 4);//移动指针4次,输出8
	cout <<"last2: "<<last2 << endl;

	int *p = &ia[2];
	cout << "*p: "<<*p << endl;

	int j = p[1];//p=&ia[2],p[1]=p+1,&ia[2]+1=&ia[3]=6
	cout << "j= " << j << endl;

	int k = p[-2];//p[-2]=p-2
	cout << "k= " << k << endl;//k=9

	const size_t arr_size = 5;
	int arr[arr_size] = {1,2,3,4,5};
	int *p2 = arr;
	int *p3 = p2 + arr_size;//超出末端的下一个指针,最后一个的下一个指针
	cout << "循环: " << endl;
	for (int *ptr = p2; ptr != p3; ++ptr)
	{
		cout << *ptr << endl;
	}

	const size_t arr_sz = 5;
	int int_arr[arr_sz] = {0,1,2,3,4};
	cout << "循环pbegin: " << endl;
	for (int *pbegin = int_arr, *pend = int_arr + arr_sz; pbegin != pend; ++pbegin)
		cout << *pbegin << endl;

	vector<int> ivec;
	ivec.push_back(10);
	ivec.push_back(20);
	ivec.push_back(30);
	ivec.push_back(40);
	ivec.push_back(50);
	cout << "循环迭代器: " << endl;
	for (vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); ++iter)
		cout << *iter << endl;
	return 0;
}

 

Published 356 original articles · won praise 186 · views 890 000 +

Guess you like

Origin blog.csdn.net/txwtech/article/details/104091783