How do you pass a 2D array with initialized dimensions to a function ?
URGENT Help with array...
Started by wiwbiz, Mar 14 2010 09:09 AM
5 replies to this topic
#1
Posted 14 March 2010 - 09:09 AM
|
|
|
#2
Posted 14 March 2010 - 09:29 AM
you pass it like this
in your function call
int main()
{
.................
....................
function(array[][SIZE],....);
}
the second definition of 2d array must be explicitly defined.
as how i have size defined
in your function call
int main()
{
.................
....................
function(array[][SIZE],....);
}
the second definition of 2d array must be explicitly defined.
as how i have size defined
#3
Posted 15 March 2010 - 12:43 PM
That's what I needed to know.What if you don't know value of SIZE ?
#4
Posted 15 March 2010 - 01:00 PM
pass it as a value of some pointer type, and pass the dimensions as parameters - that is if you are the one who implements the function that receive the array.
For example:
For example:
void foo(int** arr, int rows, int cols){
int i=0, j=0;
for (i=0; i < rows; i++)
for (j=0; j<cols; j++) {
/*do something*/
}
return;
}
int main(){
/*whatever you do here, lets say eventually, 'arr' is a two dimensional int
array of m rows on n columns*/
...
foo(arr, m, n);
...
}
#5
Posted 15 March 2010 - 01:10 PM
That won't work as arr is pointer to pointer, but without number of pointer pointed to.
#6
Posted 15 March 2010 - 03:21 PM
Correct but I assumed that if you don't know the size, you will have to use dynamic memory allocation, something like that:
int** arr = (int**) malloc (sizeof(int*)*rows);
for (i==0; i< rows; i++)
arr[i] = (int*) malloc (sizeof(int)*cols);
And then passing this guy to the function.


Sign In
Create Account


Back to top









