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

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

    Writing sizeof(char) is not "future-proofing" your code against possible changes in the standard. It's usually a sign of complete misunderstanding of what sizeof means and the whole fundamental model of memory objects in C - what's referred to as Representation of Types in the language of the C standard. The only reason a sizeof operator even exists or makes sense is because C specifies objects to have a "representation" in memory in terms of a smallest possible unit that is unsigned char. If not for this, storage would be a lot more abstract and there would be no use of sizeof and the related pointer arithmetic.

    sizeof is defined in units of char, i.e. sizeof(T)==N means type T occupies N chars. In light of this, sizeof(char) is completely silly; it's attempting to measure how many chars a char occupies.

提交回复
热议问题