I’m facing some trouble to find the best way to return an struct with an array or pointer to an array.
here is what i want to do:
i have a struct
typedef struct {
double *matrix;
int cols;
int rows;
int nelems;
} ResultMat;
and a function that parses a file. I need to call that function and have it return the struct
ResultMat read (string file, string tag) {
ResultMat mat;
.....
mat.cols = //some value from the file
mat.rows = //some value from the file
double array[rows][cols];
//now i fill the array
.......
mat.matrix = *array;
return mat;
}
within an array is filled with the values and i want to get back that whole struct with the
array/ pointer to the array stored in mat.matrix.
How to do that and is there maybe a better way? Im quite new to C and more familiar with OO programming, thats why I’m having trouble to find the best solution.
Hope anybody can give me some help! Thanks
I think that
double array[rows][cols];will be a problem, as you create the array on the local function stack.
This will be erased once you leave the function.
You should also be aware of, that Variable-Length arrays are not ANSI-C conform and you should better not use it in my opinion.
You should work with pointers and dynamic memory allocation.
malloc would be the keyword here.
Hope this helps