Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a 2D array to a C++ function

I have a function which I want to take, as a parameter, a 2D array of variable size.

So far I have this:

void myFunction(double** myArray){      myArray[x][y] = 5;      etc... } 

And I have declared an array elsewhere in my code:

double anArray[10][10]; 

However, calling myFunction(anArray) gives me an error.

I do not want to copy the array when I pass it in. Any changes made in myFunction should alter the state of anArray. If I understand correctly, I only want to pass in as an argument a pointer to a 2D array. The function needs to accept arrays of different sizes also. So for example, [10][10] and [5][5]. How can I do this?

like image 679
RogerDarwin Avatar asked Jan 07 '12 03:01

RogerDarwin


People also ask

How can we pass array to function in C?

To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.

Is there any way of passing 2D array to a function without knowing any of its dimensions?

A short answer is "no".

How do you pass a 2D array to a function in Python?

from array import * # import all package related to the array. arr1 = [[1, 2, 3, 4], [8, 9, 10, 12]] # initialize the array elements. print(arr1) # print the arr1 elements. # Use the insert() function to insert the element that contains two parameters.


1 Answers

There are three ways to pass a 2D array to a function:

  1. The parameter is a 2D array

    int array[10][10]; void passFunc(int a[][10]) {     // ... } passFunc(array); 
  2. The parameter is an array containing pointers

    int *array[10]; for(int i = 0; i < 10; i++)     array[i] = new int[10]; void passFunc(int *a[10]) //Array containing pointers {     // ... } passFunc(array); 
  3. The parameter is a pointer to a pointer

    int **array; array = new int *[10]; for(int i = 0; i <10; i++)     array[i] = new int[10]; void passFunc(int **a) {     // ... } passFunc(array); 
like image 87
shengy Avatar answered Nov 02 '22 10:11

shengy