suppose I have this code :
int arr[] = {{1, 4}, {2}, {3, 2, 6}};
how do I count the number of arrays within an array, which in this case would be 3. if the code dosen't work is there a way to get the answer with other methods?
i've searched on google and read articles
Your code can't work. You're declaring singe-dimensional array of type
int
and try to initialize eachint
element with a nested brace-enclosed initializer list. More of, an array may contain elements ONLY of same type. Arrays of different size are different type, so what you tried to imply is outright impossible.You can use one of dynamic containers in nested way, e.g.
std::vector<std::vector<int>>
. But for sake of knowledge or absolute, inescapable need to have a statically-sized array:Note, that in this case all elements are arrays of size 3. Rest of elements are initialized to 0. For any array following is true:
As long as
arr
name here is actually an array and not a pointer, it would work. You divide total size of array by size of its first element. Since C++17 there is a helper which does that:Ragged, but statically-sized arrays may be implemented by creating a more complex structure, eg. actually storing sizes of elements in your structure. I.e. you would have an array of element values, an array of sizes\indices and re-defined
operator[]