# malloc在C中的结构和指针

``struct Vector{ double* x; int n; };` `

` `struct Vector *y = (struct Vector*)malloc(sizeof(struct Vector));` `

` `y->x = (double*)malloc(10*sizeof(double));` `

` ` 1 2 +-----+ +------+ y------>| x------>| *x | | n | +------+ +-----+` `

` `struct Vector { double *data; // no place for x and n in readable code :-) size_t size; }; struct Vector *newVector (size_t sz) { // Try to allocate vector structure. struct Vector *retVal = malloc (sizeof (struct Vector)); if (retval == NULL) return NULL; // Try to allocate vector data, free structure if fail. retVal->data = malloc (sz * sizeof (double)); if (retVal->data == NULL) { free (retVal); return NULL; } // Set size and return. retVal->size = sz; return retVal; } void delVector (struct Vector *vector) { // Can safely assume vector is NULL or fully built. if (vector != NULL) { free (vector->data); free (vector); } }` `

`struct Vector y = (struct Vector*)malloc(sizeof(struct Vector));` 是错的

` `struct Vector y = (struct Vector*)malloc(sizeof(struct Vector)); y->x = (double*)malloc(10*sizeof(double));` `

` `struct Vector *y = malloc(sizeof *y); /* Note the pointer */ y->x = calloc(10, sizeof *y->x);` `

` `struct Vector{ int n; double x[]; }; struct Vector *y = malloc(sizeof *y + 10 * sizeof(double));` `

` `struct Vector y = (struct Vector*)malloc(sizeof(struct Vector) + 10*sizeof(double)); y->x = (double*)((char*)y + sizeof(struct Vector)); y->n = 10;` `