Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate number of rows in constant 2D c-array

Tags:

c++

c

alculating number of elements in array is easy:

int myarr[] ={1,2,3};
int myarrsize = sizeof(myarr)/sizeof(myarr[0]);

but, how can I calculate number of rows in 2D array?

int my2Darr[][3]={{1,2,3},{4,5,6}};
int my3DarrRows = ???

Is it possible?

like image 991
Valentin H Avatar asked Nov 29 '22 01:11

Valentin H


2 Answers

The same way. So either:

sizeof(my2Darr)/sizeof(my2Darr[0])

or:

sizeof(my2Darr[0])/sizeof(my2Darr[0][0])

depending on what you mean by "rows".

like image 127
Oliver Charlesworth Avatar answered Dec 10 '22 10:12

Oliver Charlesworth


Your code won't compile unless you specify second array size which you know its size already:

int my2Darr[][3]={{1,2,3},{4,5,6}};
             ^^^

So the question come to how can I calculate number of rows in 2D array?

template <class T, unsigned N, unsigned N1>
int length(T (&)[N][N1])
{
    return N;
}

If you want column size, return N1 instead

like image 22
billz Avatar answered Dec 10 '22 10:12

billz