【发布时间】:2013-09-10 08:53:30
【问题描述】:
我正在尝试在 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) 不再起作用,当我运行我的矩阵乘法函数时。
【问题讨论】:
-
请:不要在一个typedef中声明两种类型,不要在typedef中隐藏指针类型,不要使用带有_t的名称,它们是POSIX保留的,使用
size_t对于rows和colums。 -
不,
_t不是为 POSIX 保留的。它实际上不是为任何东西保留的。虽然,应该只在类型名称中使用它。例如,size_t不是 POSIX。
标签: c arrays dynamic struct initialization