Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
686 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

By definition, sizeof(char) is always equal to 1. One byte is the size of character in C, whatever the numbers of bits in a byte there is (8 on common desktop CPU).

The typical example where one byte is not 8 bits is the PDP-10 and other old, mini-computer-like architectures with 9/36 bits bytes. But bytes which are not 2^N are becoming extremely uncommon I believe

Also, I think this is better style:

char* buf1;
double* buf2;

buf1 = malloc(sizeof(*buf1) * N);
buf2 = malloc(sizeof(*buf2) * N);

because it works whatever the pointer type is.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...