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

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

    This is all a matter of coding style. Several styles exist.

    To actually answer the question, people write

    malloc(n * sizeof(char))
    

    to keep all their code that uses malloc consistent. Next time they might need int and then they can write the code in the very same way,

    malloc(n * sizeof(int))
    

    So the reason why it is done to keep the coding style consistent. Even though sizeof(char) is indeed guaranteed to always be 1 and is therefore superfluous. It is a way to write self-documenting code.


    However, the most common way to use malloc in C is perhaps

    type* t = malloc(n * sizeof(*t));
    

    or 100% equivalent:

    type* t = malloc(n * sizeof *t);
    

    Since the operator of sizeof is not evaluated for side-effects, this code is safe, even though the variable t is not yet initialized.


    The third possible style is the pedantically correct one, which would use array pointers, since what we allocate is actually arrays:

    type (*t)[n] = malloc( sizeof(type[n]) );
    

    This is perhaps the most correct way, as far as type correctness is concerned. The size of an array is allocated, and we point at the allocated array with an array pointer.

    However, the problem with this style is that array pointers add extra complexity to the syntax: you would have to de-reference this array as (*t)[i] instead of t[i]. It makes the code harder to read. (And also as a side-note, if n is not an integer constant expression, the code won't compile on old, outdated C compilers.)

提交回复
热议问题