简体   繁体   中英

opaque c struct containing dynamic arrays

Is this the correct way to allocate memory for ac struct that contains a dynamic array? In particular, is the way I allocate memory for myStruct correct, considering that it is not yet known how big the struct actually is?

//test.h
struct Test;
struct Test * testCreate();
void testDestroy(struct Test *);
void testSet(struct Test *, int);

//test.c
#include <stdlib.h>
struct Test{
  double *var;
};

struct Test * testCreate(int size){
  struct Test *myTest = (struct Test *) malloc(sizeof(struct Test));
  myTest->var = malloc(sizeof(double)*size);
  return(myTest);
}
void testDestroy(struct Test * myTest){
  free(myTest->var);
  free(myTest);
}
void testSet(struct Test * myTest, int size){
  int i;
  for (i=0;i<size;++i){
    myTest->var[i] = i;
  }
}

struct s have fixed size, and that's what sizeof returns.

Your struct has on element, a double pointer, and that has a (platform dependent) fixed size.

Your testCreate function does things correctly. In case you don't know the size of the dynamically allocated part, you can set the pointer to NULL to denote that the memory has to be allocated later.

Yes, you correctly malloc space for the struct and then space for the array of doubles in the struct. As a practical matter, you should always test the return from malloc() for NULL before attempting to use the memory. Also, most programs like this store the size of the array in the struct as well so you can write more general code that ensures it doesn't run off the end of the allocated space.

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