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

前端 未结 12 1726
情书的邮戳
情书的邮戳 2021-01-31 07:26

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) * someDynamicAmo         


        
12条回答
  •  梦如初夏
    2021-01-31 08:15

    The standard is deliberately vague about the sizes of common types. [Wikipedia]

    While it is unlikely that the size of a char won't change, but the size of short has changed. The idiomatic way is:

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

    for any type (common or complex) type_t or

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

    So that you can decide to make changes to the type of foo later on and only change it in one place.

提交回复
热议问题