Jun 3, 2011 at 12:50am UTC
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;
}
Jun 3, 2011 at 1:45am UTC
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!!