1

I have problem with counting columns or rows quantity (it doesn't matter, because it will be always square matrix) of this array, created as below:

    float **arr1 = new float*[3];

    for (int i = 0; i < 3; i++){
        arr1[i] = new float[3];
    }

    for (int i = 0; i < 3; i++){
        for (int i = 0; i < 3; i++){
            arr1[i][j] = i;
        }
    }

I tried many options but I always get result: 1, for example:

    sizeof(arr1[0])/sizeof(arr1[0][0]);

If you know a solution, please share with me.

3D_fun
  • 553
  • 1
  • 4
  • 17
  • 2
    Possible duplicate of [How to find the 'sizeof' (a pointer pointing to an array)?](https://stackoverflow.com/questions/492384/how-to-find-the-sizeof-a-pointer-pointing-to-an-array) – lisyarus May 22 '19 at 13:04
  • 1
    The size of a pointer is the size of the pointer itself, not what it might point to. Use `std::vector` or `std::array` instead, and you won't have such problems. – Some programmer dude May 22 '19 at 13:05
  • 1
    The answer is you can not. You need to pass the dimensions if you have to use such constructs over a container class like std::vector. sizeof() in c++ is a compile time constant. In this case it will return the size of a pointer. – drescherjm May 22 '19 at 13:06
  • drescherjm: write an answer, I will give you a solution mark. – 3D_fun May 22 '19 at 13:20

1 Answers1

1

sizeof() will only return the size of the pointer.

There is only one way to get the size of the array. Create a class/structure that wraps the raw array and contains its size too.

Fortunately, you don't have to create such a structure because since C++11 you can use std::array that does it for you and is exactly what you need. You can rewrite your example as follows:

std::array<std::array<float, 3>, 3> square; // size 3x3

    for(size_t i = 0; i < square.size(); ++i)
    {
        for(size_t j = 0; j < square[0].size(); ++j)
            square[i][j] = i;
    }

The method size() gives you the size of the inner array.

I hope it helps you.

Fareanor
  • 5,900
  • 2
  • 11
  • 37