My professor told me that the following code is incorrect:
int *array = malloc(sizeof *array * length);
And that it should instead be:
int *array = malloc(length * sizeof(int));
He said that you're supposed to encase the type between brackets for sizeof
, and that length must come before the sizeof
operator. He said that I can use *array
instead of int
, but that he preferred the latter.
My biggest question is why is it that length must come before size when calling malloc
, but also why it's preferrable to use the pointer type instead of the pointer itself with sizeof
.
He also mentioned that casting (i.e. (int*)
) is desirable, but I'm not sure why it is necessary.