-3

I have to implement a code to generate a 2D array. Given N and L that are size of array. I need to generate matrix A such as

for i=1 to N
 for j=1 to L
   if(random(0,1)>0.5)
     A[i][j]=1;
   else 
     A[i][j]=0;
   end
 end
end

Let call all above code is in intial() function. Let N=10; L=100; How to make the function initial() that return a 2D array A. Thanks This is my code

const int N=10;
const int L=100;
int A[N][L]; 

int [][] initialization()
{
  for (int i=0;i<10;i++)
    for (int j=i;j<100;j++)
      {
       if(random(0,1)>0.5)
         A[i][j]=1;
       else
         A[i][j]=0;
       }
  return A;
}
Jame
  • 3,584
  • 5
  • 49
  • 92

1 Answers1

2

You already declared a two-dimensional array

const int N=10;
const int L=100;
int P[N][L]; 

So declare the function like

void initial( int a[][L], size_t n );

and call it like

initial( P, N );

Or in C++ you could define the function like

void initial( int ( &a )[N][L] );

Or even you may return reference to the array

int ( & initial( int ( &a )[N][L] ) )[N][L];

If N and L are not constants then maybe it is better to use std::vector<std::vector<int>> instead of the array.

Or if the number of columns is known at compile time then you can define a vector of std::array. For example

std::vector<std::array<int, L>>

If it is the function that has to create the array then you can dynamically allocate an array. There are two approaches. The first one

int ** initial( size_t n, size_t m )
{
    int **a = new int * [n];

    for ( size_t i = 0; i < n; i++ ) a[i] = new int [m];

    return a;
}

This function is unsafe so it is better to use smart pointers like std::unique_ptr.

Or if the number of columns is a constant then

int  ( * initial( size_t n ) )[L]
{
    int ( *a )[L] = new int [n][L];

    return a;
}
Vlad from Moscow
  • 265,791
  • 20
  • 170
  • 303