C语言 使用 malloc 分配字符数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3115564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Allocating char array using malloc
提问by Nyan
Hi recently I saw a lot of code on online(also on SO;) like:
嗨,最近我在网上(也在 SO;)上看到了很多代码,例如:
char *p = malloc( sizeof(char) * ( len + 1 ) );
Why sizeof(char) ? It's not necessary, isn't it? Or Is it just a matter of style? What advantages does it have?
为什么是 sizeof(char) ?没有必要,不是吗?或者这只是风格问题?它有什么优势?
回答by brainjam
Yes, it's a matter of style, because you'd expect sizeof(char)to always be one.
是的,这是一个风格问题,因为你希望sizeof(char)永远是一个风格。
On the other hand, it's very much an idiom to use sizeof(foo)when doing a malloc, and most importantly it makes the code self documenting.
另一方面,sizeof(foo)在执行 a 时使用它是一种习惯用法malloc,最重要的是它使代码自我记录。
Also better for maintenance, perhaps. If you were switching from charto wchar, you'd switch to
也许也更适合维护。如果你从 切换char到wchar,你会切换到
wchar *p = malloc( sizeof(wchar) * ( len + 1 ) );
without much thought. Whereas converting the statement char *p = malloc( len + 1 );would require more thought. It's all about reducing mental overhead.
没有多想。而转换语句则char *p = malloc( len + 1 );需要更多思考。这一切都是为了减少精神开销。
And as @Nyan suggests in a comment, you could also do
正如@Nyan 在评论中建议的那样,你也可以这样做
type *p = malloc( sizeof(*p) * ( len + 1 ) );
for zero-terminated strings and
对于零终止字符串和
type *p = malloc( sizeof(*p) * len ) );
for ordinary buffers.
对于普通缓冲区。
回答by Amardeep AC9MF
It serves to self-document the operation. The language defines a char to be exactly one byte. It doesn't specify how many bitsare in that byte as some machines have 8, 12, 16, 19, or 30 bit minimum addressable units (or more). But a char is always one byte.
它用于自我记录操作。该语言将字符定义为恰好是一个字节。它没有指定该字节中有多少位,因为某些机器具有 8、12、16、19 或 30 位最小可寻址单元(或更多)。但是一个字符总是一个字节。
回答by Michael Mrozek
The specification dictates that chars are 1-byte, so it is strictly optional. I personally always include the sizeoffor consistency purposes, but it doesn't matter
规范规定字符为 1 字节,因此它是严格可选的。我个人总是sizeof出于一致性目的而包含,但这并不重要

