Creating variables inside a function [C, memory handling] [Help me]


#1

I'm making some functions to handle matrices. My idea was to define a structure like this:

typedef struct {	
	int32_t rows;	
	int32_t cols;	
	float *m;
} matrix_struct;

The pointer m should contain the address to the various element of the matrix, but since its size it's arbitrary i'll have to define an array later on.

At this point i need a function to define exactly a matrix:

void matrix_create(int rows, int cols, matrix_struct *M)
{
	float matrix[rows*cols];
	(M -> rows) = rows;
	(M -> cols) = cols;
	(M -> m) = &matrix;
}

Here's my question: is it okay to define the matrix array this way? Does the float matrix array survive after matrix_create() is executed?
And if it survives, if i create a temporary matrix to work and call the function at k-rate, will the variable be destroyed at the end of the k-rate cycle or will it fill up memory?


#2

No, it's created on the stack, functions should not return pointer to a variable on the stack in c++. This can cause confusing results...
It's better to use c++ templates than doing it this way, that ensures rows and cols are known constants for the compiler.


#3

Ok thanks, i totally forgot about the heap and stack behaviour..
That's just moving my ignorance esewhere, though, i never ever worked with templates, and from what i read it's quite advanced stuff.

I want to point out that rows and cols are not constants for the compiler, they will depend on the inputs of the object (i want to create a vandermonde matrix to fit some data with a polynomial, and the row size depends on the number of sample points, while the col size depends on the degree of the polynomial, which are in the hands of the user).

At this point i wonder if it's better to defined the float m array outside the matrix_create function, and then pass the pointer to the function:

matrix_struct M;
int a = something;
int b = something_else;
float MAT1[a*b];
matrix_create(a, b, &M, MAT1);

That would make the rows and cols variables quite pointless though, if the array size is smaller than the actual rows*cols.

What do you think?