Is it necessary to multiply by sizeof( char ) when manipulating memory?

后端 未结 8 1133
走了就别回头了
走了就别回头了 2021-01-01 22:26

When using malloc and doing similar memory manipulation can I rely on sizeof( char ) being always 1?

For example I need to allocate memory for N elements of type

相关标签:
8条回答
  • 2021-01-01 22:56

    Something else to keep in mind is that the compiler statically knows the value of sizeof (char) is 1 and it also knows that multiplying a number by a static 1 implies the multiplication doesn't need to be done; the compiler will optimize it out. Concerns of performance shouldn't enter in to consideration on these grounds.

    0 讨论(0)
  • 2021-01-01 22:56

    From "New C standard. An economic and cultural commentary".

    1. Statistics: 2.0% of sizeof are taken from char and 1.5% - from unsigned char. Page 1033 in 1.2 version of book.
    2. page 1037.

    The number of bits in the representation of a character type is irrelevant. By definition the number of bytes in byte a character type is one.

    Coding Guidelines Developers sometimes associate a byte as always containing eight bits. On hosts where the character type is 16 bits, this can lead to the incorrect assumption that applying sizeof to a character type will return the value 2. These issues are discussed elsewhere.

    0 讨论(0)
提交回复
热议问题