"address of array"的实际用例是什么?

What's a practical use-case for "address of array"?

本文关键字:是什么 address of array      更新时间:2023-10-16

(免责声明:C++中的指针是一个非常流行的话题,所以我不得不相信在我之前有人已经提出了这一点。然而,我找不到其他参考。请纠正我的错误,如果我错了,请随时关闭此线程。)

我遇到过很多例子,它们区分了指向数组第一个元素的指针和指向数组本身的指针。以下是一个程序及其输出:

//pointers to arrays
#include <iostream>
using namespace std;
int main() {
    int arr[10]  = {};
    int *p_start = arr;
    int (*p_whole)[10] = &arr;
    cout << "p_start is " << p_start <<endl;
    cout << "P_whole is " << p_whole <<endl;
    cout << "Adding 1 to both . . . " <<endl;
    p_start += 1;
    p_whole += 1;
    cout << "p_start is " << p_start <<endl;
    cout << "P_whole is " << p_whole <<endl;
    return 0;
}

输出:

p_start is 0x7ffc5b5c5470
P_whole is 0x7ffc5b5c5470
Adding 1 to both . . . 
p_start is 0x7ffc5b5c5474
P_whole is 0x7ffc5b5c5498

因此,正如预期的那样,两者加1会得到不同的结果。但我不知道p_whole这样的东西有什么实际用途。一旦我有了整个数组块的地址,也可以使用arr获得,我该如何处理这样的指针?

对于单个数组,我认为它没有多大意义。它变得有用的地方是多维数组,即数组的数组。指向其中一个子数组的指针就是指向该行的指针,递增它将获得指向下一行的指针。相反,指向内部数组第一个元素的指针是指向单个元素的指针,递增它将获得下一个元素。

int (*)[10]是比int*"更强"的类型,因为它保持了数组的大小,因此,您可以将其传递给函数,而无需传递额外的大小参数:

void display(const int(*a)[10]) // const int (&a)[10] seems better here
{
    for (int e : *a) {
        std::cout << " " << e;
    }
}

void display(const int* a, std::size_t size) // or const int* end/last
{
    for (std::size_t i = 0; i != size; ++i) {
        std::cout << " " << a[i];
    }
}