0

If I try to get the size of an array, I get the size of an array, but if I try to get it through a pointer, it doesn't work

#include <iostream>
using namespace std;

int main() {
    int a[10];

    cout << sizeof(a) / sizeof(a[0]) << endl; // works

    int *p = a;

    cout << sizeof(p) / sizeof(p[0]) << endl; // doesn`t work
}
  • 5
    Short answer: You can't. Long answer: You can't. This is why [`std::vector`](https://en.cppreference.com/w/cpp/container/vector) exists. – tadman Jul 02 '20 at 19:21
  • 2
    Forget C-style arrays exist. Use `std::array` or `std::vector` always. – Jesper Juhl Jul 02 '20 at 19:23
  • 1
    More generally, if you want a function to accept a sequence of elements you should accept a pair of iterators (`template void foo(It begin, It end)`) and then your function can work with any array or container (that has iterators compatible with your algorithm). The size of the sequence would just be `end - begin`. – cdhowie Jul 02 '20 at 19:31
  • `constexpr size_t a_size = 10; int a[a_size];` And you're golden. Just use `a_size` when you want to know the size of `a`. – Eljay Jul 02 '20 at 19:51

0 Answers0