具有二维数组 malloc 的结构

Struct with bidimensional array malloc

是否可以在 C 中 malloc 此结构?

typedef struct  {
    float a[n][M];
}myStruct;

我试过各种方法都没有成功。

#include <stdio.h>
#include <stdlib.h>

#define N 10
#define M 15

typedef struct {
    float a[N][M];
} myStruct;

int main(void)
{
    myStruct *m;

    m = malloc(sizeof(*m));
    printf("size = %zu\n", sizeof(*m));
    free(m);

    return EXIT_SUCCESS;
}

假设nM是编译时常量,你只需要

myStruct *p = malloc (sizeof myStruct);

myStruct *p = malloc (sizeof *p);

如果你的意思是'how do I allocate an N x M array of a struct where n and M are not known at compile time',答案是:

typedef struct {
   float x;
} myStruct;

...

myStruct *p = malloc (sizeof myStruct * M * N);

然后以 p[M * m + n] 的身份访问,其中 0<=m<M0<=n<N

你需要一个双指针,即一个指向指针数组的指针,像这样

typedef struct  {
    float **data;
    unsigned int rows;
    unsigned int columns;
} MyStruct;

然后malloc()

MyStruct container;

container.rows    = SOME_INTEGER;
container.columns = SOME_OTHER_INTEGER;
container.data    = malloc(sizeof(float *) * container.rows);
if (container.data == NULL)
    stop_DoNot_ContinueFilling_the_array();
for (unsigned int i = 0 ; i < container.rows ; ++i)
    container.data[i] = malloc(sizeof(float) * container.columns);

不要忘记在取消引用之前检查 container.data[i] != NULL,也不要忘记 free() 所有指针和指向指针数组的指针。