为什么写'的sizeof(char)的`如果char是1通过标准? [英] Why write `sizeof(char)` if char is 1 by standard?

查看:142
本文介绍了为什么写'的sizeof(char)的`如果char是1通过标准?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做一些C代码和阅读一些C code后,我注意到有code片段像

I was doing some C coding and after reading some C code I've noticed that there are code snippets like

char *foo = (char *)malloc(sizeof(char) * someDynamicAmount);

所以,我要问什么是更多的C-十岁上下的方式来为char数组分配内存?使用的sizeof(char)的,也应该面向未来对任何标准的变化,code或省略,并直接使用多少?

So I want to ask what's more C-ish way to allocate memory for char array? Use sizeof(char) and supposedly future-proof the code against any standard changes or omit it and use the number directly?

推荐答案

更​​CISH方法是

char* foo = malloc(someDynamicAmount * sizeof *foo);

引用的变量,而不是使不需要的类型的类型。
而如果没有铸造的malloc的结果(这是C ++ ISH)。

referencing the variable and not the type so that the type isn't needed. And without casting the result of malloc (which is C++ish).

这篇关于为什么写'的sizeof(char)的`如果char是1通过标准?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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