As C ++ pointers and arrays

With pointers to access array elements

Array is a group of the same type of data is continuously stored by arithmetic pointer, the pointer point to each element in the array, and thus may be through the array.

A pointer to the defined array elements

Definition and assignment
Example:

int a[10], *pa;
pa=&a[0]; 或 pa=a;

After the above definition and assignment: *pathat is a[0], *(pa+1)that is a[1], ..., *(pa+i)is a[i].
a[i], *(pa+i), *(a+i), pa[i]Are equivalent.


Example: with an int type array a, there are 10 elements. The output of each element in three ways:

  • Using the array name and subscript
  • Using the array name and the pointer arithmetic
  • Use pointer variable

1. Using array name and index access array elements

#include <iostream>
using namespace std;

int main() {
	int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
	for (int i = 0; i < 10; i++)
		cout << a[i] << "  ";
	cout << endl;
	return 0;
}

2. Use the array name and pointer arithmetic to access array elements

#include <iostream>
using namespace std;

int main() {
	int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
	for (int i = 0; i < 10; i++)
		cout << *(a+i) << "  ";
	cout << endl;
	return 0;
}

3. Use the pointer variables to access the array elements

#include <iostream>
using namespace std;

int main() {
	int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
	for (int *p = a; p < (a + 10); p++)
		cout << *p << "  ";
	cout << endl;
	return 0;
}
Published 263 original articles · won praise 28 · views 20000 +

Guess you like

Origin blog.csdn.net/weixin_43283397/article/details/104451565