char * charStringA = malloc(100);
char * charStringB = malloc(sizeof(char)*100);
Both are equally correct.
Two important points that should be considered in this evaluation are:
- size of
char
is guaranteed to be one byte by the C standard.
- A
void
pointer can be assigned to any pointer without an explicit cast in C and the casting is unnecessary. Casting the return value of malloc
is considered as an bad practice because of the following:
What's wrong with casting malloc's return value?
The above answer applies to the options mentioned in the OP. An better practice is to use sizeof
without making any assumptions about the size of any type. This is the reason and purpose that sizeof
exists. In this case the best practice will be to use:
char * charStringB = malloc(sizeof(*charStringB)*100);
Note that *charStringB
is same as char
but this gives you the flexibility that if you want to change the type in future then there is fewer number of places where you need to remember to make modifications.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…