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

后端 未结 8 1161
走了就别回头了
走了就别回头了 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:54

    Using the sizeof(char) makes your code more readable and portable.

    On x86, we all know that a character is 1 byte. But explicitly writing it down helps make your intentions clearer, which is always a good thing.

    Also, what if your code gets put on some other platform where a character isn't 1 byte. What if a character was only 4 bits instead?

    Agreed, it's not necessary, but it doesn't slow your run time down and it will pay off in that rare case you need to port your code to a different architecture.

提交回复
热议问题