c-具有二维数组malloc的结构



有可能在C中malloc这个结构吗?

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

我尝试过不同的方法,但都没有成功。

假设nM是编译时常数,您只需要

myStruct *p = malloc (sizeof myStruct);

myStruct *p = malloc (sizeof *p);

如果你的意思是"如何分配一个结构的N x M数组,其中N和M在编译时是未知的",答案是:

typedef struct {
   float x;
} myStruct;
...
myStruct *p = malloc (sizeof myStruct * M * N);

则作为p[M * m + n]接入,其中0<=m<M0<=n<N

#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 = %zun", sizeof(*m));
    free(m);
    return EXIT_SUCCESS;
}

您需要一个双指针,即指向指针数组的指针,如

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()所有的poitner和指向poitner数组的指针。

最新更新