是否有必要通过的sizeof(char)的操纵内存时繁殖? [英] Is it necessary to multiply by sizeof( char ) when manipulating memory?
问题描述
我使用malloc和做类似的存储操作时候可以依靠的sizeof(char)的是始终为1?
例如我需要为字符
类型的N个元素分配内存。由乘的sizeof(char)的
必要的:
的char *缓冲区=的malloc(N * sizeof的(炭));
或者我可以依靠的sizeof(char)的始终为1,只需跳过乘法
的char *缓冲区=的malloc(N);
我完全明白,的sizeof
编译期间评估,那么编译器甚至编出乘法,因此性能损失将是最小的,最有可能为零。
我问的主要是关于code清晰度和可移植性。这是有史以来相乘的必要的为字符
键入<?/ p>
虽然它不是必需的,我认为这是很好的做法,在的sizeof(char)的离开,因为它使code更易读,而且避免使用一个神奇的数字。此外,如果code需要在以后进行更改,这样,而不是一个char它mallocing的东西大小成指针的对象,它更容易改变code比,如果你只有一个1
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 char
. Is multiplying by sizeof( char )
necessary:
char* buffer = malloc( N * sizeof( char ) );
or can I rely on sizeof( char ) always being 1 and just skip the multiplication
char* buffer = malloc( N );
I understand completely that sizeof
is evaluated during compilation and then the compiler might even compile out the multiplication and so the performance penalty will be minimal and most likely zero.
I'm asking mainly about code clarity and portability. Is this multiplication ever necessary for char
type?
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".
这篇关于是否有必要通过的sizeof(char)的操纵内存时繁殖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!