user1322915
user1322915

Reputation: 1291

how to find 2d array size in c++

How do I find the size of a 2D array in C++? Is there any predefined function like sizeof to determine the size of the array?

Also, can anyone tell me how to detect an error in the getvalue method for arrays while trying to get a value which is not set?

Upvotes: 39

Views: 241536

Answers (12)

SridharKritha
SridharKritha

Reputation: 9631

Suppose you were only allowed to use an array, then you could find the size of a 2-D array in the following way.

  int ary[][5] = { {1, 2, 3, 4, 5},
                   {6, 7, 8, 9, 0}
                 };

  int rows = sizeof ary / sizeof ary[0]; // 2 rows  

  int cols = sizeof ary[0] / sizeof(int); // 5 cols

Upvotes: 69

doug
doug

Reputation: 4289

There is a standard template to determine sizes of the dimensions of arrays: std::extent_v

#include <type_traits>
#include <iostream>
int main()
{
    int a[3][4];
    std::cout << "rows:" << std::extent_v<decltype(a), 0> << '\n';
    std::cout << "cols:" << std::extent_v<decltype(a), 1> << '\n';
    std::cout << "size in bytes:" << sizeof(a) << '\n';
}

Output:

rows:3
cols:4
size in bytes:48

Upvotes: 1

Vikas G
Vikas G

Reputation: 51

int rows = sizeof(arr)/sizeof(arr[0]);
int cols = sizeof(arr[0])/sizeof(arr[0][0]);

Upvotes: 5

Ayesha Qaisar
Ayesha Qaisar

Reputation: 1

This can also be tried to get the row and column size of a 2-D array

matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] 
int rows =  matrix.size();
int cols = matrix[0].size();
cout<<rows<< " "<<cols;    

Ouput: 3 4

Upvotes: 0

Osman Khalid
Osman Khalid

Reputation: 798

Here is one possible solution of first part

#include<iostream>

using namespace std;
int main()
{
    int marks[][4] = {
                      10, 20, 30, 50,
                      40, 50, 60, 60,
                      10, 20, 10, 70
                     };

int rows =  sizeof(marks)/sizeof(marks[0]);
int cols = sizeof(marks)/(sizeof(int)*rows);


    for(int i=0; i<rows; i++)
    {
        for(int j=0; j<cols; j++)
        {
            cout<<marks[i][j]<<" ";
        }
        cout<<endl;
    }



    return 0;
}

Upvotes: 1

poorgoat
poorgoat

Reputation: 47

Along with the _countof() macro you can refer to the array size using pointer notation, where the array name by itself refers to the row, the indirection operator appended by the array name refers to the column.

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    int beans[3][4]{
        { 1, 2, 3, 4 }, 
        { 5, 6, 7, 8 }, 
        { 9, 10, 11, 12 }
    };

    cout << "Row size = " << _countof(beans)  // Output row size
        << "\nColumn size = " << _countof(*beans);  // Output column size
    cout << endl;

    // Used in a for loop with a pointer.

    int(*pbeans)[4]{ beans };

    for (int i{}; i < _countof(beans); ++i) {

        cout << endl;

        for (int j{}; j < _countof(*beans); ++j) {

            cout << setw(4) << pbeans[i][j];
        }
    };

    cout << endl;
}

Upvotes: 2

blank
blank

Reputation: 1

int arr[5][4];

For the row subscript(4 raise to 2, include cmath to use pow):

sizeof(arr1)/pow(4,2)   

Column subscript:

sizeof(*arr1)/4

4 means 4 bytes, size of int.

Upvotes: 0

bitbyter
bitbyter

Reputation: 910

#include <bits/stdc++.h>
using namespace std;


int main(int argc, char const *argv[])
{
    int arr[6][5] = {
        {1,2,3,4,5},
        {1,2,3,4,5},
        {1,2,3,4,5},
        {1,2,3,4,5},
        {1,2,3,4,5},
        {1,2,3,4,5}
    };
    int rows = sizeof(arr)/sizeof(arr[0]);
    int cols = sizeof(arr[0])/sizeof(arr[0][0]);
    cout<<rows<<" "<<cols<<endl;
    return 0;
}

Output: 6 5

Upvotes: 24

Ridowan Ahmed
Ridowan Ahmed

Reputation: 95

#include<iostream>
using namespace std ;
int main()
{
    int A[3][4] = { {1,2,3,4} , {4,5,7,8} , {9,10,11,12} } ;
    for(int rows=0 ; rows<sizeof(A)/sizeof(*A) ; rows++)
    {
        for(int columns=0 ; columns< sizeof(*A) / sizeof(*A[0]) ; columns++)
        {
            cout<<A[rows][columns] <<"\t" ;
        }
        cout<<endl ;
    }
}

Upvotes: 1

pg30123
pg30123

Reputation: 65

The other answers above have answered your first question. As for your second question, how to detect an error of getting a value that is not set, I am not sure which of the following situation you mean:

  1. Accessing an array element using an invalid index:
    If you use std::vector, you can use vector::at function instead of [] operator to get the value, if the index is invalid, an out_of_range exception will be thrown.

  2. Accessing a valid index, but the element has not been set yet: As far as I know, there is no direct way of it. However, the following common practices can probably solve you problem: (1) Initializes all elements to a value that you are certain that is impossible to have. For example, if you are dealing with positive integers, set all elements to -1, so you know the value is not set yet when you find it being -1. (2). Simply use a bool array of the same size to indicate whether the element of the same index is set or not, this applies when all values are "possible".

Upvotes: 0

ApprenticeHacker
ApprenticeHacker

Reputation: 22011

Use an std::vector.

std::vector< std::vector<int> > my_array; /* 2D Array */

my_array.size(); /* size of y */
my_array[0].size(); /* size of x */

Or, if you can only use a good ol' array, you can use sizeof.

sizeof( my_array ); /* y size */
sizeof( my_array[0] ); /* x size */

Upvotes: 18

Baz1nga
Baz1nga

Reputation: 15579

sizeof(yourObj)/sizeOf(yourObj[0])

should do the trick

Upvotes: 17

Related Questions