lnlidawei

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

cpp:  指针数组和数组指针

 

 

 

 

一、基本概念

 

  1、指针数组

    1.1、指针数组:指针数组是以指针为元素的数组;指针数组是一个数组;指针数组的元素是指针。

    1.2、定义:       int  *pt[10];       // pt是数组,包含10个整型指针元素;

 

  2、数组指针

    2.1、数组指针:数组指针是指向数组的指针;数组指针是一个指针.

    2.2、定义:        int  (*pt)[2];        //  pt指向一个数组,这个数组的每个元素还包含两个子元素。

    2.3、指针数组示例:

 

 

 

二、程序代码

 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: ptone has ten pointers of type of int
31     int *ptone[10];
32     
33     int two[5][2] = {
34             1,  2,
35             3,  4,
36             5,  6,
37             7,  8,
38             9,  0
39         };
40     
41      int (*pttwo)[2] = two;
42     
43     // 'pttwo' is a pointer, 'pttwo' points an array with 2 elements of type of int
44     //
45     // pttwo in { two[0], two[1], two[2], two[3], two[4] }
46     // two[0] = { two[0][0], two[0][1] }
47     // two[1] = { two[1][0], two[1][1] }
48     // two[2] = { two[2][0], two[2][1] }
49     // two[3] = { two[3][0], two[3][1] }
50     // two[4] = { two[4][0], two[4][1] }
51   
52     int one[10];
53     init(one);
54     
55     ptone[9] = &one[9];
56     
57     cout << "one[9] = " << one[9] << endl;
58     cout << "ptone[9] = " << *ptone[9] << endl;
59     
60     print(pttwo);
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 one[9] = 9
4 ptone[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

 

posted on 2024-01-09 23:05  lnlidawei  阅读(19)  评论(0编辑  收藏  举报