regular pointer vs pointer to an array

what is the difference between "int* p" and "int (*pa)[anySize]"
in regards to point to an array

1
2
3
  int arr[anySize];
  int* p = arr;
  int (*pa)[anySize] = arr;
The types of the pointers are different.
p points to an integer.
pa points to an array of (constant) anySize.
So p doesn't retain the array dimension information.
pa does.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

template<typename T, std::size_t Size>
void f(T(*)[Size]) { std::cout << "array\n"; }

template<typename T>
void f(T*) { std::cout << "pointer\n"; }

int main() {
    int a[10] {};

    int *p = a;
    std::cout << sizeof *p << " bytes\n";   // 4 bytes
    f(p);                                   // pointer

    int (*pa)[10] = &a;
    std::cout << sizeof *pa << " bytes\n";  // 40 bytes
    f(pa);                                  // array
}

Last edited on
Put other way, how much is ++ ?

The ++p will advance sizeof(int).
The ++pa will advance 10*sizeof(int).
Considering that the pa did point to first element of array a, and a has 10 elements, the pa does point after the increment to one-past-the-end of array a.
So p doesn't retain the array dimension information.
pa does.

note it's useful for more than sizeof/++

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
#include <iostream>

template<class T>
void print(const T& c) {
    for(auto n : c)
        std::cout << n << ' ';
    std::cout << '\n';
}
template<class T>
void print(T* p, int n) {
    for(int i = 0; i != n; ++i)
        std::cout << p[i] << ' ';
    std::cout << '\n';
}

int main() {
    int a[10] = {1,2,3,4,5,6,7,8,9,0};
    
    int (*pa)[10] = &a;
    // prints the array, because array size is not lost, guaranteed to be correct
    print(*pa);
    
    int *p = a;
    // size is lost, needs to be supplied by hand (and it's impossible to verify that what you supplied is correct!)
    print(p, 10);
}

live demo https://wandbox.org/permlink/ncucSlnr5hvqowAC
thank you all for the input
Topic archived. No new replies allowed.