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

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

    The common idiom is

    T *p = malloc(N * sizeof *p);
    

    or

    T *p;
    ...
    p = malloc(N * sizeof *p);
    

    This way you don't have to worry about the type.

提交回复
热议问题