对malloc的疑问。 C (Linux)
下面的代码中,buf = malloc(n * sizeof(char));
是什么意思,
是否需要n*sizeof(char),如果是的话..精心制作的。
int n;
char* buf;
fstat(fd, &fs);
n = fs.st_size;
buf = malloc(n * sizeof(char));
编辑1如果我写(n*sizeof(double))会怎样
In the following code,what is the meaning of buf = malloc(n * sizeof(char));
is n*sizeof(char) necessary,if yes.. please elaborate.
int n;
char* buf;
fstat(fd, &fs);
n = fs.st_size;
buf = malloc(n * sizeof(char));
EDIT1 And What if I write (n*sizeof(double))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
malloc
函数分配字节并将您要分配的字节数作为输入。sizeof
运算符返回给定类型的字节数。在这种情况下,char
是 1 个字节,但在int
的情况下,它很可能是 4 个字节,或者double
很可能是 8 个字节。表达式n * sizeof(char)
将char
的数量转换为所需的字节数。在所示的情况下,使用
char
可能不需要计算字节数,但是应该这样做,因为它有助于传达您的意图。该表达式所做的是分配所需的内存量,以容纳最多
n
个char
数,并返回一个指针buf
>,到分配的内存的开头。The
malloc
function allocates bytes and takes as input the number of bytes you would like to allocate. Thesizeof
operator returns the number of bytes for a given type. In this case achar
is 1 byte, but in the case of anint
it is most likely 4 bytes ordouble
is most likely 8 bytes. The expressionn * sizeof(char)
converts the number ofchar
into the number of bytes that are desired.In the case illustrated, using
char
, computing the number of bytes is probably not needed, but it should be done as it helps to convey your intent.What the expression is doing is allocating the desired amount of memory needed to hold at most
n
number ofchar
's and returning you a pointer,buf
, to the beginning of that allocated memory.ISO 标准将
byte
定义为与char
大小相同。malloc
永远不需要sizeof(char)
The ISO standard defines a
byte
as the same size as achar
.You never need
sizeof(char)
formalloc