简体   繁体   中英

How to find out the size of two dimensional an int array in C++?

I'm having a problem with a C++ program involving two dimensional arrays.

As part of the program I have to use a function which accepts as parameters two tables and adds them, returning another table.

I figured I could do something like this:

int** addTables(int ** table1, int ** table2) 
{ 
    int** result;
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < columns; j++)
        {
            result[i][j] = table1[i][j] + table2[i][j]; 
        }
    }
    return result;
}

but I don't know how to find out the size of the table (rows and columns) for my "for" loops.

Does anybody have an idea of how to do this?

This is part of the code I was testing, but I'm not getting the right number of columns and rows:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main(int argc, char **argv) 
{
    const int n = 3; // In the addTables function I'm not supposed to know n.
    int **tablePtr = new int*[n]; // I must use double pointer to int.
    for (int i = 0; i < n; i++)
    {
        tablePtr[i] = new int[n];
    }

    srand((unsigned)time(0));
    int random_integer;

    for(int i = 0; i < n; i++) // I assign random numbers to a table.
    {
        for (int j = 0; j < n; j++)
        {
            random_integer = (rand()%100)+1;
            tablePtr[i][j] = random_integer;
            cout << tablePtr[i][j] << endl;
        }
    }   

    cout << "The table is " << sizeof(tablePtr) << " columns wide" << endl;
    cout << "The table is " << sizeof(tablePtr) << " rows long" << endl;

    return 0;
}

I appreciate any help, and please keep in mind that I'm new to C++.

There is no way to "find" the size of what a pointer points to in C or C++. A pointer is just an address value. You would have to pass in the size - or in your case the number of rows or columns into the addTables function - like:

int** addTables(int ** table1, int ** table2, int rows, int columns)

This is why the commentors are suggesting something like a vector . C++ offers better data types than raw pointers - for one thing a vector tracks the number of items that it contains so it doesn't have to be passed as separate parameters.

In your example program, the sizeof operator returns the size of the type of the variable supplied. So for sizeof(tablePtr) it returns the size of an int** which will likely be 4 or 8 bytes. The sizeof operation is evaluated a compile time so there is no way it could know how large the buffer that tablePtr points to is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM