简体   繁体   中英

Struct with bidimensional array malloc

Is it possible to malloc this struct in C?

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

I've tried different ways with no success.

#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;
}

Assuming n and M are compile time constants, you just want

myStruct *p = malloc (sizeof myStruct);

or

myStruct *p = malloc (sizeof *p);

If you actually meant 'how do I allocate an N x M array of a struct where n and M are not known at compile time' , the answer is:

typedef struct {
   float x;
} myStruct;

...

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

then access as p[M * m + n] where 0<=m<M , 0<=n<N .

You need a double pointer, ie a pointer to an array of pointers, like this

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

then to malloc() it

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);

dont forget to check container.data[i] != NULL before dereferencing and also do not forget to free() all the poitners and the pointer to array of poitners too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM