C: Initializing a dynamic array inside a struct
I'm trying to implement my own basic version of matrix multiplication in C
and based on another implementation, I have made a matrix data type. The
code works, but being a C novice, I do not understand why.
The issue: The I have a struct with a dynamic array inside it and I am
initializing the pointer. See below:
// Matrix data type
typedef struct
{
int rows, columns; // Number of rows and columns in the matrix
double *array; // Matrix elements as a 1-D array
} matrix_t, *matrix;
// Create a new matrix with specified number of rows and columns
// The matrix itself is still empty, however
matrix new_matrix(int rows, int columns)
{
matrix M = malloc(sizeof(matrix_t) + sizeof(double) * rows * columns);
M->rows = rows;
M->columns = columns;
M->array = (double*)(M+1); // INITIALIZE POINTER
return M;
}
Why do I need to initialize the array to (double*)(M+1)? It seems that
also (double*)(M+100) works ok, but e.g. (double *)(M+10000) does not work
anymore, when I run my matrix multiplication function.
No comments:
Post a Comment