I've seen different ways to malloc a struct, but I'm confused which way is the best way to do it. (Please add explanations when your give your opinions.)
The code below uses a variable's type as size in malloc().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
struct Vector {
double *data;
size_t size;
};
int main()
{
int sz = 12;
struct Vector *retVal = malloc (sizeof (struct Vector)); //#####
retVal->data = malloc (sz * sizeof (double)); //#####
// Set size and return.
retVal->size = sz;
printf("retVal->size: %d\n", sz);
return 0;
}
|
However, the two lines using malloc() marked w/ "//#####" can be replaced by the following ways and get compiled and printed out the correct value:
(1)
struct Vector *retVal = malloc (sizeof (struct Vector *)); //#####
retVal->data = malloc (sz * sizeof (double *)); //#####
(2)
struct Vector *retVal = malloc (sizeof (retVal)); //#####
retVal->data = malloc (sz * sizeof (retVal->data)); //#####
(3)
struct Vector *retVal = malloc (sizeof (*retVal)); //#####
retVal->data = malloc (sz * sizeof (retVal->data)); //#####
My questions: Are all the 4 methods correct? Which way is the best way?
Thanks in advance for your help!