我正在尝试用C语言实现自己的矩阵乘法基本版本,根据另一个实现,我已经创建了一个矩阵数据类型。代码可以正常工作,但由于我是C的新手,我不明白为什么。
问题:我有一个结构体,里面有一个动态数组,我正在初始化它的指针。请参见下面:
// 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;
}
为什么我需要将数组初始化为(double*)(M+1)?似乎(double*)(M+100)也可以正常工作,但是当我运行矩阵乘法函数时,(double *)(M+10000)就不能再工作了。
size_t
来表示rows
和columns
。 - Jens Gustedt