Passing 2D dynamic created array (using pointer) as const

Dec 8, 2015 at 7:11pm
Hello,
i have created 2D dynamic array using pointers like this:

double **matice = new double*[m];
for (int i = 0; i < m; i++) matice[i] = new double[n];

and have filled it with values. The reason i am using this
instead of vector is that i need to, its given by task and number
of columns and rows is changing due to input of user, so i need to
everytime create temporary array, pass values from original array, delete
original array, created it again and pass values from temporary array and new
ones like retard.

Thats all fine, but now i need to somehow pass this array into function
in way, that function wont be able to change values of array, make it const
(also in task). Something like this bellow, but array wont be changed.

void gauss(double **matice, int n, int m) {
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
matice[i][j] = 0;
}
}
}

int main (){
gauss (matice, n, m);
}
Thank you for any answers, if this question is stupid in any way, i am sure
someone will gladly delete it.

P.S. If there is some better solution to this dynamic array problem, i´d be glad
for help.
P.S.2. I apologize greatly for my bad Englando.
Last edited on Dec 8, 2015 at 8:27pm
Dec 8, 2015 at 7:43pm
Could you show an example of when you use your variable. The code you are currently showing should work. You pass a double** to the function, this mean the pointer will be copied. This doesn't matter, since you dereference it (twice actually), yielding the same memory location you modify. The problem doesn't appear to be in your current code. Of course, I could be missing something.
Dec 8, 2015 at 7:49pm
This code is working, but i need to pass it as constant, so that function wont be able to change values.
Last edited on Dec 8, 2015 at 7:49pm
Dec 8, 2015 at 7:51pm
Should it not be able to change the actual values, because in that case the loop setting the entire array to 0 will not compile. Or should it not be able to change the pointers?
Dec 8, 2015 at 8:04pm
The idea was to pass it somehow as const, like you would pass normal array. That loop was just for testing. Something like:

void gauss(double const **matice) {}

but thats not possible. And browsing internet and looking for answers just made me think, that
its retarded idea.

The task says, that function has constant input of pointer to array.

Dunno might be just better to ask the teacher next week.

Dec 8, 2015 at 9:03pm
If it should be completely constant, you should declare it as:

 
void gauss(const double* const * const, /*other parameters*/)


This declares a constant pointer to a constant pointer to constant doubles. So nothing may be modified.
Dec 8, 2015 at 9:36pm
Oh i see, thanks a lot. :)
Dec 9, 2015 at 11:29am
When the type definition gets complicated like that, you might find it useful to create your own typedef, e.g.

typedef const double* const * const ConstMatrix;
Topic archived. No new replies allowed.