user1563544
user1563544

Reputation: 377

Inputing the Size of a 2-dimentional Array

In my code I input the sizes of both dimensions and then declare a two-dimensional array. My question is, how do I use that array as a function parameter? I know that I need to write the number of columns in the function specification but how do I pass the number of columns?

 void gameDisplay(gameCell p[][int &col],int a,int b) {
         for(int i=0;i<a;i++) {
                for(int j=0;j<b;j++) {
                         if(p[i][j].getStat()==closed)cout<<"C ";
                         if(p[i][j].getStat()==secure)cout<<"S ";
                         if(p[i][j].getBomb()==true&&p[i][j].getStat()==open)cout<<"% ";
                         if(p[i][j].getBomb()==false&&p[i][j].getStat()==open) {
                                 if(p[i][j].getNum()==0)cout<<"0 ";
                                 else cout<<p[i][j].getNum()<<" ";
                         }
                 cout<<endl;
                 }
         }
 }

 int main() {
         int row,col,m;
         cout<<"Rows: ";cin>>row;cout<<"Columns: ";cin>>col;
         m=row*col;
         gameCell p[row][col];
         gameConstruct(p[][col],m);
         gameDisplay(p[][col],row,col);
 }

I tried this way but it doesn't work.

Thank you.

Upvotes: 1

Views: 178

Answers (6)

Roee Gavirel
Roee Gavirel

Reputation: 19445

instead of accessing p[i][j] you should access p[i*b + j] - this is actually what the compiler do for you since int[a][b] is flattened in the memory to an array in size of a*b

Also, you can change the prototype of the function to "void gameDisplay(gameCell p[],int a,int b)"

The fixed code:

void gameDisplay(gameCell p[],int a, int b) {
         for(int i=0;i<a;i++) {
                for(int j=0;j<b;j++) {
                         if(p[i*a +j].getStat()==closed)cout<<"C ";
                         if(p[i*a +j].getStat()==secure)cout<<"S ";
                         if(p[i*a +j].getBomb()==true&&p[i][j].getStat()==open)cout<<"% ";
                         if(p[i*a +j].getBomb()==false&&p[i][j].getStat()==open) {
                                 if(p[i*a +j].getNum()==0)cout<<"0 ";
                                 else cout<<p[i*a +j].getNum()<<" ";
                         }
                 cout<<endl;
                 }
         }
 }

 int main() {
         int row,col,m;
         cout<<"Rows: ";cin>>row;cout<<"Columns: ";cin>>col;
         m=row*col;
         gameCell p[row][col];
         gameConstruct(p[][col],m);
         gameDisplay(p[],row,col);
 }

Upvotes: 0

Joseph Mansfield
Joseph Mansfield

Reputation: 110658

In C++, you cannot have variable length arrays. That is, you can't take an input integer and use it as the size of an array, like so:

std::cin >> x;
int array[x];

(This will work in gcc but it is a non-portable extension)

But of course, it is possible to do something similar. The language feature that allows you to have dynamically sized arrays is dynamic allocation with new[]. You can do this:

std::cin >> x;
int* array = new int[x];

But note, array here is not an array type. It is a pointer type. If you want to dynamically allocate a two dimensional array, you have to do something like so:

std::cin >> x >> y;
int** array = new int*[x]; // First allocate an array of pointers
for (int i = 0; i < x; i++) {
  array[i] = new int[y]; // Allocate each row of the 2D array
}

But again, this is still not an array type. It is now an int**, or a "pointer to pointer to int". If you want to pass this to a function, you will need the argument of the function to be int**. For example:

void func(int**);
func(array);

That will be fine. However, you almost always need to know the dimensions of the array inside the function. How can you do that? Just pass them as extra arguments!

void func(int**, int, int);
func(array, x, y);

This is of course one way to do it, but it's certainly not the idiomatic C++ way to do it. It has problems with safety, because its very easy to forget to delete everything. You have to manually manage the memory allocation. You will have to do this to avoid a memory leak:

for (int i = 0; i < x; i++) {
  delete[] array[i];
}
delete[] array;

So forget everything I just told you. Make use of the standard library containers. You can easily use std::vector and have no concern for passing the dimensions:

void func(std::vector<std::vector<int>>);

std::cin >> x >> y;
std::vector<std::vector<int>> vec(x, std::vector<int>(y));
func(vec);

If you do end up dealing with array types instead of dynamically allocating your arrays, then you can get the dimensions of your array by defining a template function that takes a reference to an array:

template <int N, int M>
void func(int (&array)[N][M]);

The function will be instantiated for all different sizes of array that are passed to it. The template parameters (dimensions of the array) must be known at compile time.

Upvotes: 2

rbtLong
rbtLong

Reputation: 1572

is this what you're looking for?

int* generate2DArray(int rowSize, int colSize)
{
    int* array2D = new int[rowSize, colSize];
    return array2D;
}

example . . .

#include <iostream>
#include <stdio.h>

int* generate2DArray(int rowSize, int colSize);
int random(int min, int max);

int main()
{
    using namespace std;

    int row, col;
    cout << "Enter row, then colums:";
    cin >> row >> col;

    //fill array and display
    int *ptr = generate2DArray(row, col);
    for(int i=0; i<row; ++i)
        for(int j=0; j<col; ++j)
        {
            ptr[i,j] = random(-50,50);
            printf("[%i][%i]: %i\n", i, j, ptr[i,j]);
        }

    return 0;
}


int* generate2DArray(int rowSize, int colSize)
{
    int* array2D = new int[rowSize, colSize];
    return array2D;
}

int random(int min, int max)
{
    return (rand() % (max+1)) + min;
}

Upvotes: 0

David G
David G

Reputation: 96810

If you're using C-style arrays, you might want to make a reference in the parameter:

int (&array)[2][2]; // reference to 2-dimensional array

Upvotes: 0

Tristram Gr&#228;bener
Tristram Gr&#228;bener

Reputation: 9711

I'm guessing from Problems with 'int' that you have followed the advices of the validated question and that you are using std::vector

Here is a function that returns the number of columns of an "array" (and 0 if there is a problem).

int num_column(const std::vector<std::vector<int> > & data){
    if(data.size() == 0){
        std::cout << "There is no row" << std::endl;
        return 0;
    }
    int first_col_size = data[0].size();
    for(auto row : data) {
        if(row.size() != first_col_size){
            std::cout << "All the columns don't have the same size" << std::endl;
            return 0;
        }
    }
    return first_col_size;   
}

Upvotes: 0

Linkas
Linkas

Reputation: 946

I made a little program:

#include <iostream>
using namespace std;
void fun(int tab[][6], int first)
{}
int main(int argc, char *argv[])
{
    int tab[5][6];
    fun(tab, 5);
    return 0;
}

In function definition you must put size of second index. Number of column is passed as argument.

Upvotes: 0

Related Questions