什么是"阵列地址的实际用例"?

时间:2015-11-10 06:41:39

标签: c++ pointers

(免责声明:C ++中的指针是一个非常受欢迎的主题,因此我不得不相信在我之前的某个人已经提出了这一点。但是,我无法找到另一个参考文献。请更正如果我错了,请随时关闭此帖子。)

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

jquery.js

输出:

typed.js

因此,正如预期的那样,两者都加1会产生不同的结果。但我很遗憾看到像//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 获得,我可以用这样的指针做什么?

2 个答案:

答案 0 :(得分:11)

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

答案 1 :(得分:2)

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];
    }
}