How to pass a two sided array to a function where it is altered and returned.

What syntax is used to pass a two sided array to a function where the array vaules are changed and returned to the calling main() program.

What is the syntax in the function declaration for the passed in array parameter? What is the syntax for the array in the function itself when the array values are changed? What is the syntax in the main() program when the function is called and the array parameter is passed?

Thanks from a beginner.
The same as ever. For a fixed size array:
1
2
3
4
5
6
7
8
9
10
11
12
void myfunc( int a[ 10 ][ 10 ] )
  {
  // do stuff to 'a' here
  }

int main()
  {
  int square[ 10 ][ 10 ];
  ...
  myfunc( square );
  ...
  }


Hope this helps.
If you need a dynamically sized array.

You can use a vector of vectors.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void changeMe(vector<vector<int> > *array) {
  (*array)[0][3] = 1;
}

int main() { 
  
  vector< vector<int> > vIntList;
  vector<int> dim1;
  
  for (int i =0; i < 5; ++i)
    dim1.push_back(i);
  
  vIntList.push_back(dim1);
  
  changeMe(&vIntList);
   
  return 0;
}


Or, my preferred method, as I my work is required for high performance calculations, is to go the manual way. Unfortunately you will need to manage memory yourself and get dirty with pointers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void changeMe(int **p) {
  p[1][1] = 2;
}

int main() { 
  int iSize = 10; // Can be defined at runtime etc

  int **array = new int*[iSize ];
  for (int i = 0; i < iSize ; ++i)
    array[i] = new int[iSize ];
      
  changeMe(array);
  
  for (int i = 0; i < iSize; ++i)
    delete [] array[i];
  delete [] array;
  
  return 0;
}
Last edited on
I'm working with a fixed array. Your answer solved my problem. Thanks.
Topic archived. No new replies allowed.