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

前端 未结 12 1728
情书的邮戳
情书的邮戳 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:28

    You're correct, by standard, the multiplication is irrelivant. That said, it looks like a habit someone got into to be consistent. If you always use the sizeof(), regardless of type, you never forget.

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

提交回复
热议问题