Thank you for clarifying my confusion, Jochen!! :D I appreciate it.
Millenia Nova
Posts
-
Question about malloc a struct -
Question about malloc a structThanks for your response. Just to make sure I understand your answer, I listed .....I'm thinking the second malloc() used in my previous example can be replaced by the line below?
sizeof(12 * sizeof(retVal->data));
Thank you!
-
Question about malloc a structThe code below uses a variable's type as size in malloc(). And I printf the size of //line 1, b and c to find out their sizes malloc will allocation the space for them in heap. Question part 1: One person told me I should use // line a's size to malloc in // #####, while the other person said I should use //line c instead. They do have the same size in printf(). Which one is correct? Why? Question part 2: // line b and // line c both have the same type of variable pointers, but why do they have different sizes? struct Vector { double *data; size_t size; }; int main() { int a, b, d; int sz = 12; a = sizeof(struct Vector); // line a printf("%d\n", a); //a = 16 b = sizeof(struct Vector*); // line b printf("%d\n", b); //b = 8 c = sizeof(*retVal); // line c printf("%d\n\n", c); //c = 16 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; } Thank you for your help. :)