Alex Rivera | Logout

Why write `sizeof(char)` if char is 1 by standard?

Asked 2011-08-30T13:23:54.780
49

I was doing some C coding and after reading some C code I've noticed that there are code snippets like

char *foo = (char *)malloc(sizeof(char) * someDynamicAmount);

So I want to ask what's more C-ish way to allocate memory for char array? Use sizeof(char) and supposedly future-proof the code against any standard changes or omit it and use the number directly?

Edit
Report

1 Answer

26

IMHO the best practice is to write sizeof(*foo). Then you're covered also if the type of foo changes and the sizeof is not corrected.

answered 2011-08-30T13:28:55.647

Your Answer