I am trying to figure a way to retrieve a specific element from a pointer 3d array in C in the manner of element[i][j][k].
My current approach looks like this:
void printElement(double *inputMatrix, int i, int j, int k) {
double val = *(*( (inputMatrix i) j) k);
printf("%f\n", val);
}
However, if I call printElement(), I am getting the following error:
utils.c:38:16: error: invalid type argument of unary ‘*’ (have ‘double’)
What is wrong with the stars?
CodePudding user response:
In this case you actually need more arguments than just the required index. In general, when you are storing a N-dimensional matrix as a linear array, you need the sizes of the matrix along all N-1 dimensions to access an element.
For 1D matrix, N-1 is 0. So you just need the index. The code for that is:
void printEle(double *mat, int i) {
double val = *(mat i);
printf("%lf\n", val);
}
For 2D matrix, N-1 is 1. So along with two indices, you need size of the first dimension. The code for that is:
void printEle(double *mat, int M, int i, int j) {
double val = *(mat M*i j);
printf("%lf\n", val);
}
Continuing on, for 3D matrix, N-1 is 2. So the proper code in this case is:
void printEle(double *mat, int M, int N, int i, int j, int k) {
double val = *(mat M*N*i M*j k);
printf("%lf\n", val);
}
However, if you know values of M, N, O in compile time, you can simplify as:
void printEle(double mat[M][N][O], int i, int j, int k) {
double val = mat[i][j][k];
printf("%lf\n", val);
}
If you only know M and N, then also it can be written as:
void printEle(double *mat[M][N], int i, int j, int k) {
double val = mat[i][j][k];
printf("%lf\n", val);
}
Also, on a sidenote, format specifier for double
is %lf
and not %f
.