I'm trying to create a null matrix with the method zeros (); and then show it on the screen. Nothing is shown.
double * zeros(int m,int n){
double matrix[3][3] ={0};
return matrix;
}
void printMatrice(int row,int column, double matrix [3][3]) {
for (row=0; row<3; row++)
{
for(column=0; column<4; column++)
{printf("%f ", matrix[row][column]);}
printf("\n");
}
}
MAIN:
int main () {
printMatrice(3,3,zeros(3,3));
return 0;
}
Show this on screen:
Process returned -1073741819 (0xC0000005)
These are the warnings
Of method printMatrice():
--warning: passing argument 3 of 'printMatrice' from incompatible pointer type [-Wincompatible-pointer-types]|
Of method zeros():
-- warning: returning 'double (*)[3]' from a function with incompatible return type 'double *' [-Wincompatible-pointer-types]
--warning: function returns address of local variable [-Wreturn-local-addr]|
Working with multidimensional arrays in c++ is a pain in the ass. One of the easiest ways is to use a simple array and convert coordinates into linear index manually.
This way, you do not have to hard-wire matrix dimensions into functions, you do not have to alloc/free memory, you can reuse and reinterpret data, etc. Of course, it would be better to encapsulate it in a class, but this is just an example.
void reset(double matrix[], int rows, int cols, double value) {
for (int i = 0; i < rows * cols; i++)
matrix[i] = value;
}
void print(double matrix[], int rows, int cols) {
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++)
printf("%f ", matrix[r * cols + c]);
printf("\n");
}
}
int main() {
double m[3 * 3];
reset(m, 3, 3, 0.0);
print(m, 3, 3);
printf("\n");
double n[2*5];
reset(n, 2, 5, 1.0);
print(n, 2, 5);
return 0;
}
User contributions licensed under CC BY-SA 3.0