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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
// if you want to pass an array in this way the second dimension must be provided, known at compile time
int sum(int a[][3], int m){
//do some things here
int summ = 0 ;
int n = 3 ;
for(int i = 0 ; i < m ; i++)
for(int j = 0 ; j <n ; j++)
summ+= a[i][j];
return summ;
}
// passing a n array which is created dynamically
int sum(int** a, int m, int n ){
//do some things here
int summ = 0 ;
for(int i = 0 ; i < m ; i++)
for(int j = 0 ; j <n ; j++)
summ+= a[i][j];
return summ;
}
int main()
{
// if you use [dimension][dimension] to define an array
// dimension must be know at compile time
int a[3][3] = {{3, 6, 7},{-5, 0,1},{-3,5,2}};
// passing the array unto the function and getting the return value
int i = sum( a, 3);
cout<< i << endl ;
int n = 3 ;// you may use cin>> n or whatever to assign a value to n
int m = 3 ;//you may use cin>> m or whatever to assign a value to m
// create an array dynamically the size n and m must not be know at compile time
int** b = new int*[m] ;
for(int i = 0 ; i < m ; i++)
b[i] = new int[n] ;
for(int i = 0 ; i < m ; i++)
for(int j = 0 ; j <n ; j++)
b[i][j] = ( i + j ) * i;
// passing the array unto the function
i = sum(b, 3, 3 );
cout<< i << endl;
// you must delete the array that you created dynamically using the operator new
for(int i = 0 ; i < m ; i++)
delete [] b[i];
delete [] b;
return 0;
}
|