May 20, 2017 at 6:50pm UTC
I was creating a project and wanted to create a function that accepts 1 2d array of different sizes and a integer to specify its size but it didn't work. I would like to know if there is some special way to do it? Are their any forums that can help me with this?
1 2 3 4 5 6
void initializeSlot(char A[][],int size)
{
for (int row = 0 ; row < size; row++)
for (int col = 0;col < size; col++)
A[row][col] = 'X' ;
}
Last edited on May 20, 2017 at 6:50pm UTC
May 20, 2017 at 8:13pm UTC
Some ideas:
(1) Collapse it to a 1-d array with cell index, e.g.
int n = row * size + col;
(2) Use a 1-d array of strings
(3) This rather clunky hybrid of vectors and fixed-size arrays:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#include <iostream>
#include <vector>
using namespace std;
void initializeSlot( vector< vector<char > > &A, int size )
{
for ( int row = 0 ; row < size; row++ )
{
for ( int col = 0; col < size; col++ )
{
A[row][col] = 'X' ;
}
}
}
int main()
{
const int size = 5;
vector< vector<char > > A( size, vector<char >( size ) );
initializeSlot( A, size );
for ( int row = 0 ; row < size; row++ )
{
for ( int col = 0; col < size; col++ )
{
cout << A[row][col] << '\t' ;
}
cout << '\n' ;
}
}
X X X X X
X X X X X
X X X X X
X X X X X
X X X X X
(4) If size is a compile-time constant then I think there is a clever method with templates, but it's so clever I've forgotten it.
Of choice I usually use method 1 however.
Last edited on May 20, 2017 at 8:18pm UTC
May 20, 2017 at 9:29pm UTC
you need the rows, cols, and data regardless, which begs a struct or class.
pointer syntax works too.. if you mess with casting enough to force fit it, something like
void foo (type ** x)
you can also force it with a typedef, but those seem out of style these days.
Last edited on May 20, 2017 at 9:30pm UTC