EDIT after a sleeping night
this code works
#include <stdlib.h>
#define MAX_X 5
#define MAX_Y 6
void main ( void ){
int i,j,k;
double *aux;
double *MM[MAX_X][MAX_Y];
// Populate MM
for (i = 0; i < MAX_X; i++)
for (j = 0; j < MAX_Y; j++ ){
aux = calloc (100,sizeof(double));
if (aux != NULL)
for (k = 0; k < 100; k++)
aux[k] = 10.0 * (i + j + k);
MM[i][j] = aux;
}
// do something
// Free MM
for (i = 0; i < MAX_X; i++)
for (j = 0; j < MAX_Y; j++ ){
if (MM[i][j] != NULL)
free (MM[i][j]);
}
}
What I want is :
#include <stdlib.h>
#define MAX_X 5
#define MAX_Y 6
double *[][] calc_MM ( void ){
double *MM[MAX_X][MAX_Y];
for (i = 0; i < MAX_X; i++)
for (j = 0; j < MAX_Y; j++ ){
aux = calloc (100,sizeof(double));
if (aux != NULL)
for (k = 0; k < 100; k++)
aux[k] = 10.0 * (i + j + k);
MM[i][j] = aux;
}
return MM;
}
void free_MM ( double *MM[MAX_X][MAX_Y] ){
int i,j;
for (i = 0; i < MAX_X; i++)
for (j = 0; j < MAX_Y; j++ ){
if (MM[i][j] != NULL)
free (MM[i][j]);
}
}
void main ( void ){
int i,j,k;
double *aux;
double *MM[MAX_X][MAX_Y];
// Populate MM
MM = calc_MM ();
// do something
// Free MM
free_MM ( MM );
}
what type should I define so I can pass MM and return it from a function?
double *MM[MAX_X][MAX_Y];
OLD question I have a code that works fine
double *foo (int i, int j){
double *aux;
do something
return aux;
}
void main (void){
double *MM[MAX_X][MAX_Y];
..
..
// Calc as MM
for (i = 0; i < MAX_X; i++)
for (j = 0; j < MAX_Y; j++ )
MM[i][j] = foo (i,j);
}
and I would like to put the loop inside a function.
double *foo (int i, int j){
double *aux;
do something
return aux;
}
double ***calc_MM ( some input ) {
int i,j;
double ***MM;
for (i = 0; i < MAX_X; i++)
for (j = 0; j < MAX_Y; j++ )
MM[i][j] = foo (i,j);
return MM;
}
void main (void){
double *MM[MAX_X][MAX_Y];
..
..
// Calc as MM
MM = calc_MM ( some input )
}
MAX_X and MAX_Y are #define constant and later will be read from envp
Sorry if I am not clear, but I have to use MM and it would become much more modular if I could pass and return it from a function.
I need some help in how I can define
double *MM[MAX_X][MAX_Y];
so I pass and return it from a function.
I tried some combination of * and const *, etc but I always have a compiler error.
Returning `double * (*)[35]` from a function with incompatible return type `double ** const*` [-Werror=incompatible-pointer-types].
I think this one may answer my question but I did not understand Designating a pointer to a 2D array