Jump to content

URGENT Help with array...

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
5 replies to this topic

#1
wiwbiz

wiwbiz

    Learning Programmer

  • Members
  • PipPipPip
  • 67 posts
How do you pass a 2D array with initialized dimensions to a function ?

#2
hbk

hbk

    Learning Programmer

  • Members
  • PipPipPip
  • 71 posts
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

#3
wiwbiz

wiwbiz

    Learning Programmer

  • Members
  • PipPipPip
  • 67 posts
That's what I needed to know.What if you don't know value of SIZE ?

#4
bobdark

bobdark

    Programmer

  • Members
  • PipPipPipPip
  • 164 posts
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:
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
wiwbiz

wiwbiz

    Learning Programmer

  • Members
  • PipPipPip
  • 67 posts
That won't work as arr is pointer to pointer, but without number of pointer pointed to.

#6
bobdark

bobdark

    Programmer

  • Members
  • PipPipPipPip
  • 164 posts
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.