0
#include <iostream>
using namespace std;

const int triTable[4][6] = {
    {},
    {0, 8, 3},
    {0, 1, 9},
    {1, 8, 3, 9, 8, 1},
};

int main() {
  const int *f = triTable[3];
  int size = sizeof(f)/sizeof(*f);
  cout << size; 
}

This gives me wrong numbers. It should print 6. How can I get it?

trshmanx
  • 600
  • 7
  • 16
  • 4
    Since `f` is a pointer, `sizeof f` will be the size of the *pointer* and not what it might point to. Since you're programming in C++ there's a very easy solution: Use either `std::array` or `std::vector` instead, where you can easily get the number of elements. – Some programmer dude Apr 05 '21 at 11:47
  • `sizeof(f)/sizeof(*f)` is equal to `sizeof(int *)/sizeof(int)` which has no relationship to either dimension of `triTable`. To get the first dimension (i.e. 4) you need to calculate `sizeof(triTable)/sizeof(*triTable)`. To get the second dimension (i.e. 6) you need to calculate `sizeof(*triTable)/sizeof(**triTable)`. You can't use `f` to get either, since the conversion of `triTable[3]` to `int *` loses the size information. – Peter Apr 05 '21 at 12:28

2 Answers2

1

How to get size of const array in c++?

Like this:

std::size(triTable[3])

This gives me wrong numbers.

You generally cannot get the size of an array by using a pointer to element of that array.

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

As stated sizeof f is the size of the pointer not the size of the object where it points to, as also said, using STL containers is a much better option given that they have size members that keep track of the size of the container.

That being said, if you're adamant in using a C style array, a solution would be to wrap it in a struct or class and return the size from there, i.e:

struct myArray
{
    const int triTable[4][6] = {
        {},
        {0, 8, 3},
        {0, 1, 9},
        {1, 8, 3, 9, 8, 1},
    };

    const int size = std::size(triTable[3]); // size data member

    int arraySize() const{
        return std::size(triTable[3]); // size method
    }

};

int main()
{
    myArray a;
    std::cout << a.size << "\n";
    std::cout << a.arraySize();
}

Output:

6
6
anastaciu
  • 23,467
  • 7
  • 28
  • 53
  • This not working correct. Change `triTable[3]` to triTable[1] what should return 3, but still returns max 6. – trshmanx Apr 07 '21 at 06:46
  • You declare `triTable[4][6]`, all the lines have 6 elements regardless of if they are initialized or not. That's how arrays work. In your initialization all the uninitialized members will be implicitly initialized to 0. https://godbolt.org/z/YaYz7hMYT – anastaciu Apr 07 '21 at 07:16