dynamic matrix and function parameters

Hello!

I'm writing a function that should reallocate and set a dynamic matrix passed as the parameter of the function self.

But when I execute it the matrix is reallocated only into the function and when it exit from the function, the address of the matrix isn't changed.

Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

void allocateMatrix(int *matrix[], int nrow, int ncol)
{
    int i;
    
    matrix = new int*[nrow];
    for (i=0; i<nrow; i++)
        matrix[i] = new int[ncol];
}

void main()
{
    int **mat;
    int nrow  = 3, ncol = 2;
    
    allocateMatrix(mat, nrow, ncol);
}


thanks
Change the function signature into this -> void allocateMatrix(int **& matrix, int nrow, int ncol)
thanks for the reply :)
please, could you tell me why should I change matrix into an integer double pointer reference?
what happens in it is a reference in this case?

thanks
http://cplusplus.com/forum/beginner/27867/#msg149555

EDIT: Note that when passing parameters in a function T t[] is exactly the same as T * t, therefore T *t[] is exactly the same as T ** t.
Last edited on
So the point is that in the function I wasn't operating on the matrix and I solve it by passing the memory address of the double integer pointer...right?

But in this case isn't enough to pass the address of the matrix? like this:

1
2
3

...
allocateMatrix(&mat, nrow, ncol);


and change the function into this:

1
2
3
4
5
6
7
8
void allocateMatrix(int ***matrix, int nrow, int ncol)
{
    int i;
    
    *matrix = new int*[nrow];
    for (i=0; i<nrow; i++)
        *matrix[i] = new int[ncol];
}


in this way it might work on the mat memory address and so declare a dynamical matrix "connected" to matrix itself.

Thanks
Yes, this works too. In fact, it's the same as the reference approach (your compiler would generate exactly the same code), except it's somewhat less readable. References are usually implemented as pointers internally. Think of a reference as a pointer that automatically dereferences itself every time it's used.
ok, it's clear. I catch it :) thanks a lot
Topic archived. No new replies allowed.