I have the following basic C example:
#include <stdio.h>
struct Example {
double arr[4][4];
int size;
};
int main()
{
struct Example e = {
{{1., 0., 0., 0.},
{0., 1., 0., 0.},
{0., 0., 1., 0.},
{0., 0., 0., 1.}},
4
};
double** arr = e.arr;
printf("%8.5f %8.5f %8.5f %8.5f\n", arr[0][0], arr[0][1], arr[0][2], arr[0][3]);
printf("%8.5f %8.5f %8.5f %8.5f\n", arr[1][0], arr[1][1], arr[1][2], arr[1][3]);
printf("%8.5f %8.5f %8.5f %8.5f\n", arr[2][0], arr[2][1], arr[2][2], arr[2][3]);
printf("%8.5f %8.5f %8.5f %8.5f\n", arr[3][0], arr[3][1], arr[3][2], arr[3][3]);
}
What do I have to do to make the printf successfully print out the values in the matrix? If I declare arr as double** I get a segfault. If I try double* then it complains when I try to do double indexing. I've also tried double arr[4][4] = e.arr, but the compiler just tells me that it's an invalid initializer. What's the proper way to do this?
(I realize size is redundant in this example, I just wanted the struct to have more than one member.)
double (*arr)[4] = e.arr. Note thate.arris the same as&e.arr[0], but&e.arr[0]is the address of an entire array with 4doubles (a line of the 2D matrix), so you need a pointer that can point to an entire array of length 4.