Alexander said:
Hello,
I've got a quite simple question. I want to have something like
int
main()
{
double array[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}};
double **field;
field = array;
}
The compiler complains an not allowed conversion in the assignment
field = array;
It's neccessary that field is of type double**. How to manage an
initialization like the above?
This is a faq question and answer. Read faq question 6.18 located:
http://www.eskimo.com/~scs/C-faq/q6.18.html
As the faq suggests, make this:
double (*field)[3] = array;
An example is shown below using in function PrintARRAY, using a
typedef.
If, as you say, it is neccessary that field be type double**, then
you can still do it at the expense of making access to the elements
a little more difficult. This is shown in functions PrintARRAY2 and
PrintARRAY3 below.
#include <stdio.h>
#define ROW 3
#define COL 4
typedef double (*ARR)[COL];
void PrintARRAY(ARR row);
void PrintARRAY2(double **field);
void PrintARRAY3(double **field);
int main(void)
{
double array[ROW][COL] = {{1,2,3,11}, {4,5,6,22}, {7,8,9,33}};
ARR this = array;
double **field = (double **)array;
puts("Using function PrintARRAY");
PrintARRAY(this);
puts("\nUsing function printARRAY2");
PrintARRAY2(field);
puts("\nUsing function printARRAY3");
PrintARRAY3(field);
return 0;
}
void PrintARRAY(ARR row)
{
int i,j;
for(i = 0; i < ROW;i++)
{
for(j = 0; j < COL; j++)
printf("%.2f ",row
[j]);
putchar('\n');
}
return;
}
void PrintARRAY2(double **field)
{
int i,j;
double (*arr)[COL] = (double (*)[COL])field;
for(i = 0; i < ROW;i++,arr++)
{
for(j = 0; j < COL; j++)
printf("%.2f ",(*arr)[j]);
putchar('\n');
}
return;
}
void PrintARRAY3(double **field)
{
int i,j;
double *arr= (double *)field;
for(i = 0;i < ROW; i++)
{
for(j = 0; j < COL;j++)
printf("%.2f ",arr[i*COL+j]);
putchar('\n');
}
return;
}