malloc(sizeof(int)) vs malloc(sizeof(int *)) vs (int *)malloc(sizeof(int)) [英] malloc(sizeof(int)) vs malloc(sizeof(int *)) vs (int *)malloc(sizeof(int))
问题描述
我承认所有这三个都有不同的含义.但是,我不明白这些适用于哪些特定情况.任何人都可以为每一个分享一个例子吗?谢谢.
I acknowledge that all three of these have a different meaning. But, I don't understand on what particular instances would each of these apply. Can anyone share an example for each of these? Thank you.
malloc(sizeof(int))
malloc(sizeof(int *))
(int *)malloc(sizeof(int))
推荐答案
malloc(sizeof(int))
意味着您正在分配堆外的空间来存储 int
.您保留了 int
所需的字节数.这会返回一个您应该转换为 正如一些人所指出的,C 中的典型做法是让隐式转换来处理这一点.int *
的值.(指向 int
的指针.)
malloc(sizeof(int))
means you are allocating space off the heap to store an int
. You are reserving as many bytes as an int
requires. This returns a value you should cast to As some have noted, typical practice in C is to let implicit casting take care of this.int *
. (A pointer to an int
.)
malloc(sizeof(int*))
意味着您正在分配堆外的空间来存储指向 int
的指针.您保留了指针所需的字节数.这将返回一个您应该转换为 int **
的值.(一个指向 int
的指针的指针.)
malloc(sizeof(int*))
means you are allocating space off the heap to store a pointer to an int
. You are reserving as many bytes as a pointer requires. This returns a value you should cast to an int **
. (A pointer to a pointer to an int
.)
(int *)malloc(sizeof(int))
与第一次调用完全相同,但结果显式转换为指向 int
的指针.
(int *)malloc(sizeof(int))
is exactly the same as the first call, but with the the result explicitly casted to a pointer to an int
.
请注意,在许多体系结构上,int
与指针的大小相同,因此它们看起来(错误地)都是一样的.换句话说,您可能不小心做错了事,结果代码仍然可以工作.
Note that on many architectures, an int
is the same size as a pointer, so these will seem (incorrectly) to be all the same thing. In other words, you can accidentally do the wrong thing and have the resulting code still work.
这篇关于malloc(sizeof(int)) vs malloc(sizeof(int *)) vs (int *)malloc(sizeof(int))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!