cpp: 指针数组和数组指针
一、基本概念
1、指针数组:指针数组是以指针为元素的数组;指针数组是一个数组;指针数组的元素是指针;定义形式: int *pt[10]; // pt是数组,包含10个整型指针元素;
2、数组指针:数组指针是指向数组的指针;数组指针是一个指针;定义形式: int (*pt)[2]; // pt指向一个数组,这个数组的每个元素还包含两个子元素。
二、程序代码
1 #include <iostream>
2
3 using std::cout, std::endl;
4
5 void init(int* array)
6 {
7 for(int i=0; i<10; i++)
8 {
9 array[i]=i;
10 }
11 }
12
13 // print: output an array with 2 elements of type of int
14 void print(int (*p)[2])
15 {
16 cout << "output: ";
17 for(int i=0; i<5;i++)
18 {
19 int *p2=p[i];
20 for(int j=0; j<2; j++)
21 {
22 cout << p2[j] << ' ' ;
23 }
24 }
25 cout << endl;
26 }
27
28 void msg()
29 {
30 // array: ten pointers of type of int
31 int *a[10];
32
33 int aa[5][2] = {
34 1,2,
35 3,4,
36 5,6,
37 7,8,
38 9,0
39 };
40
41 int (*ppt)[2]=aa;
42
43 // ppt is pointer, ppt points an array with 2 elements of type of int
44 //
45 // ppt = { aa[0], aa[1], aa[2], aa[3], aa[4]}
46 // aa[0] = {aa[0][0], aa[0][1]}
47 // aa[1] = {aa[1][0], aa[1][1]}
48 // aa[2] = {aa[2][0], aa[2][1]}
49 // aa[3] = {aa[3][0], aa[3][1]}
50 // aa[4] = {aa[4][0], aa[4][1]}
51
52 int i[10];
53 init(i);
54
55 a[9] = &i[9];
56
57 cout << "i[9] = " << i[9] << endl;
58 cout << "a[9] = " << *a[9] << endl;
59
60 print(ppt);
61 }
62
63
64 int main()
65 {
66
67 msg();
68
69 return 0;
70 }
三、运行结果
1 g++ -std=c++20 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
2
3 i[9] = 9
4 a[9] = 9
5 output: 1 2 3 4 5 6 7 8 9 0
四、参考资料
1、c++在线编译器: https://coliru.stacked-crooked.com/
2、pointer declaration : https://en.cppreference.com/w/cpp/language/pointer