如果你想用一个malloc 分配整个结构,你可以使用
typedef struct
{
int rows;
int cols;
double data[1];
} Matrix;
与其他答案相比,这允许使用单个 free。
如果您的编译器支持大小为 0 的数组,您也可以使用 double data[0];。
从 C99 开始,您可以在结构中使用没有维度的数组:double data[];,请参阅 https://stackoverflow.com/a/2061038/10622916
与其通过添加结构字段类型的大小来计算malloc 的大小,不如将sizeof 或offsetof 与结构类型Matrix 一起使用,因为可能会有一些填充。 (可能不是您的情况,但这取决于编译器实现和您的结构字段。)
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h> // for offsetof
typedef struct
{
int rows;
int cols;
double data[1];
// or with C99: double data[];
} Matrix;
Matrix *initMatrix(int rows, int cols)
{
Matrix *ptr;
double *data;
ptr = (Matrix *)malloc(
offsetof(Matrix, data) // = size of Matrix without double data[1];
// with C99's "double data[];" or with the non-standard
// "double data[0];" you can replace offsetof(...) with: sizeof(Matrix)
+ sizeof(double) * rows * cols); // dynamic array size
if(ptr == NULL) {
perror("malloc failed");
} else {
// save rows and columns for later accessing the matrix
ptr->rows = rows;
ptr->cols = cols;
data = ptr->data;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
*(data) = 0;
data++;
}
}
}
return ptr;
}
int main(void)
{
Matrix *mptr = initMatrix(2, 2);
// use matrix
// a single free is sufficient with the approach above
free(mptr); mptr = NULL;
return 0;
}
你可以计算数组索引,而不是增加指针data
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
ptr->data[i * cols + j] = 0;
}
}
或者对于 0 初始化,你可以使用 memset
memset(ptr->data, 0, sizeof(double) * rows * cols);
或者使用calloc(1, offsetof(Matrix, data) + sizeof(double) * rows * cols);而不是malloc来获得零初始化内存。