C:在struct中初始化动态数组

时间:2013-09-06 09:40:34

标签: c arrays dynamic struct initialization

我正在尝试在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)不再起作用。

2 个答案:

答案 0 :(得分:3)

这种东西的推荐方法是与offsetof一起使用的未大小数组。它确保正确对齐。

#include <stddef.h>
#include <stdlib.h>

// Matrix data type
typedef struct s_matrix
{
    int rows, columns;      // Number of rows and columns in the matrix
    double array[];         // Matrix elements as a 1-D array
} 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)
{
    size_t size = offsetof(matrix_t, array) + sizeof(double) * rows * columns;
    matrix* M = malloc(size);
    M->rows = rows;
    M->columns = columns;
    return M;
}

答案 1 :(得分:0)

你需要初始化它,否则(等待它)未初始化

除了生成未定义的行为之外,你不能使用未初始化的指针。

将其初始化为M + 1 正好,并且代码非常好。任何其他值都将无法使用您为此目的分配的内存。

我的观点是结构末尾的double *不会“自动”指向这个记忆,这就是你的问题隐含的信念,为什么它应该被初始化。因此,必须将其设置为正确的地址。

相关问题