(免责声明: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获得),该如何处理该指针?

最佳答案

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

07-24 09:45