const double ** pointer

I made a simple function copying the values of the array a, which is double **, to the array b.

void copy2(int dim1,int dim2,double **a,double **b);

It worked as I expected. Then I put "const" keyword, since the values of the array a should not be altered:

void copy2(int dim1,int dim2,const double **a,double **b);

Afterwards, the code was not complied producing error:

main.cpp:39: error: invalid conversion from ‘double**’ to ‘const double**’
main.cpp:39: error: initializing argument 3 of ‘void copy2(int, int, const double**, double**)’

In addition, I found that I could compile the code if I put "const" other places:

void copy2(int dim1,int dim2,double * const *a,double **b);
void copy2(int dim1,int dim2,double ** const a,double **b);

I am very confused. Do you know what the code should be like to meet my intention?


PS. For reference, I attached my whole code:

#include <iostream>
#include <new>

using namespace std;

double **alloc2(int dim1,int dim2)
{
double **ptr = new double *[dim1];
ptr[0] = new double [dim1*dim2];
for (int i=1;i<dim1;i++) ptr[i] = ptr[0]+i*dim2;
return ptr;
}

void copy2(int dim1,int dim2,double **a,double **b)
{
for (int i=0;i<dim1;i++)
for (int j=0;j<dim2;j++) b[i][j] = a[i][j];
return;
}

void print2(int dim1,int dim2,double **a)
{
for (int i=0;i<dim1;i++)
for (int j=0;j<dim2;j++) cout << a[i][j] << endl;
return;
}

#define N1 5
#define N2 4

int main(void)
{
double **a = alloc2(N1,N2);
double **b = alloc2(N1,N2);

for (int i=0;i<N1;i++)
for (int j=0;j<N2;j++) a[i][j] = (i+1)*(j+1);

copy2(N1,N2,a,b);

print2(N1,N2,b);

return 0;
}
Assuming a is being copied to b (a is src, b is dest), then it should be the below:

 
void copy2(int dim1,int dim2,const double* const* a,double* const *b);


It's easier if you read pointers "backwards" and say '*' as "pointer to"

That is: const double* const* a means that:

a is a pointer to a const pointer to a const double.

This means that a can be changed, but a[x] and a[x][x] cannot be changed.

double* const *b means that:

b is a pointer to a const pointer to a double.

This means that b[x] cannot be changed, but b and b[x][x] can be.


Confusing? Yes. Which is one of the many reasons not to do this. Obligatory link:
http://www.cplusplus.com/forum/articles/17108/
Thank you so much, Disch!!!
Although I need some time to fully understand the link you provided, your explanation is exactly what I really wanted to know.
Your way of reading/interpreting pointers is really awesome!!
Your way of reading/interpreting pointers is really awesome!!


I wish I could take credit. I got it from here:

http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.5
Topic archived. No new replies allowed.