使用 malloc 分配 char 数组 [英] Allocating char array using malloc

查看:27
本文介绍了使用 malloc 分配 char 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下行:

char *p = malloc( sizeof(char) * ( len + 1 ) );

为什么要使用 sizeof(char)?这没有必要,不是吗?还是只是风格问题?

Why is sizeof(char) used? It's not necessary, is it? Or Is it just a matter of style?

它有什么优势?

推荐答案

是的,这是风格问题,因为您希望 sizeof(char) 始终为一.

Yes, it's a matter of style, because you'd expect sizeof(char) to always be one.

另一方面,在执行 malloc 时使用 sizeof(foo) 是一种习惯用法,最重要的是它可以使代码自我记录.

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.

也许也更适合维护.如果你从 char 切换到 wchar,你会切换到

Also better for maintenance, perhaps. If you were switching from char to wchar, you'd switch to

wchar *p = malloc( sizeof(wchar) * ( len + 1 ) );

没有多想.而转换语句 char *p = malloc( 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.

正如@Nyan 在评论中建议的那样,您也可以这样做

And as @Nyan suggests in a comment, you could also do

type *p = malloc( sizeof(*p) * ( len + 1 ) );

对于以零结尾的字符串和

for zero-terminated strings and

type *p = malloc( sizeof(*p) * len ) );

对于普通缓冲区.

这篇关于使用 malloc 分配 char 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆