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

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

    While its not necessary, I consider it good practice to leave in the sizeof( char ) because it makes the code more readable and avoids the use of a magic number. Also, if the code needs to be changed later so that instead of a char it's mallocing the size of something into a pointer for that object, it's easier to change the code than if you have just a "1".

提交回复
热议问题