Posts 数组指针与函数指针
Post
Cancel

数组指针与函数指针

1.数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
//1. 没有值传递,本质上是引用传递  不太好判断数组大小
void method11(int arr[]){
    cout << arr << endl;   // 0x16b09b590  传递arr[0]
}

//2. 传递数组收尾指针
void method22(int * p1,int * p2){
    while (p1 != p2){
        cout << *p1 << endl;
        ++ p1;
    }
}

// 3. 传递数组指针与数组大小 显式传递
//略

//4. 直接传递一个数组指针
void method44(int (*p)[10]){
    cout << *(*p) << endl;
}

//5. 引用传递的问题
void method55(int (&arr)[10]){
    for (const auto &item : arr){
        cout << item << endl;
    }
}

void test48(){
    int arr[10] = {1,2,3,4};
    int (*p)[10] ;
    p = &arr;
//    method11(arr);
//    method22(begin(arr), end(arr));
//    method44(p);
    method55(arr);
}

1.1 数组指针

数组没有拷贝,要么返回指针,要么返回引用

很重要,翻了一个小时才翻明白

1
2
3
4
5
6
7
8
9
    int arr[10] = {1,2,4,5};
    int* p[10];    // 含有十个指针的数组   ->  int *p[10]
    int (*p2)[10];    // p2为一个指针,指向含有十个整数的数组  指针的指针 有点绕晕了

    p2 = &arr;      // 存放arr指针的指针 
    cout << *(*p2) << endl;    //  第一次解引用得到数组第一位地址 第二次解引用得到arr[0];

    int *p4 = arr;              //  arr 本身就是指针
    cout << *p4 << endl;

1.2 返回数组指针的几种形式

  • 尾置返回类型

还是再说一下,为什么不直接返回数组arr的指针要返回arr指针的指针? 我要返回的是一个指向一个arr[10]的地址,这个地址里面的指针代表的是一个10长度的数组,而不是一个arr的头指针 你要接收返回值,也就只能用相同维度的数组来接收

1
2
3
4
5
6
7
8
9
//3.尾置返回类型 Cpp11
auto test603()->int(*)[10]{   // 返回一 指向数组的一个指针
    int arr[10] = {1,2,4};
    return &arr;
}
void test604(){
    auto p = test603();
    cout << *(*p) <<endl;
}
  • decltype
1
2
3
4
5
6
7
8
9
10
//4. decltype 返回
int arr[10] = {1,3,4,5};
decltype(arr)* test605(){
    int arr[10] = {1,2,4};
    return &arr;
}
void test606(){
    auto p = test605();
    cout << *(*p) <<endl;
}

2.函数指针

2.1 定义

1
2
3
4
5
6
7
8
9
10
// 1.函数指针的定义
bool  test608(int a,int b){
    return a>b? true: false;
}
void test607(){
    bool  (*p)(int a,int b);  // 声明函数指针
    p = test608;        // 指向函数
//    p = &test608;     等价
    cout << p(1,2) << endl;
}

2.2 重载

略,与函数类似

2.3 返回指向函数的指针

  • 别名
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    //1. 别名
    using p = bool(*)(int,int); //函数指针
    using pf = bool(int,int); // 函数类型 不是指针
    p test609(){
      return test608;
    }
    void test6101(){
      p f;
      f = test609();
      cout << f(1,2) << endl;
    }
    
  • 尾置返回 与数组类似 略
  • 使用decltype
    1
    2
    3
    4
    5
    6
    7
    8
    
    decltype(test608) *test6102(){
      return test608;
    }
    void test6103(){
      p f;
      f = test609();
      cout << f(1,2) << endl;
    }
    
This post is licensed under CC BY 4.0 by the author.

Contents

Trending Tags