Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

pointers

(Disclaimer: Pointers in C++ is a VERY popular topic and so I'm compelled to believe that someone before me has already raised this point. However, I wasn't able to find another reference. Please correct me and feel free to close this thread if I'm wrong.)

I've come across lots of examples that distinguish between pointer to first element of array and pointer to the array itself. Here's one program and its output:

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

Output:

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

So, as expected, adding 1 to both gives different results. But I'm at a loss to see a practical use for something like p_whole. Once I have the address of the entire array-block, which can be obtained using arr as well, what can I do with such a pointer?

like image 583
ankush981 Avatar asked Nov 10 '15 06:11

ankush981


2 Answers

For single arrays, I don't think there's much point to it. Where it becomes useful is with multi-dimensional arrays, which are arrays of arrays. A pointer to one of the sub-arrays is a pointer to the row, and incrementing it gets you a pointer to the next row. In contrast, a pointer to the first element of the inner array is a pointer to a single element, and incrementing it gets you the next element.

like image 65
Barmar Avatar answered Sep 19 '22 05:09

Barmar


int (*)[10] is a "stronger" type than int* as it keeps size of the array, so you may pass it to function without passing additional size parameter:

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

versus

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];
    }
}
like image 44
Jarod42 Avatar answered Sep 22 '22 05:09

Jarod42