的malloc(sizeof的(INT))VS的malloc(sizeof的为(int *))对为(int *)malloc的(的sizeof(int)的) [英] malloc(sizeof(int)) vs malloc(sizeof(int *)) vs (int *)malloc(sizeof(int))
问题描述
我承认,所有这三个具有不同的意义。但是,我不要将各自的应用,这些哪个特定实例理解。任何人都可以分享每一个这些的例子吗?谢谢你。
的malloc(sizeof的(INT))VS的malloc(sizeof的为(int *))对为(int *)malloc的(的sizeof(int)的)
的malloc(sizeof的(INT))
意味着你离堆分配空间来存储 INT
。您保留的字节数为 INT
要求。 <击>这将返回你应该转换为价值为int *
。 (一个指向 INT
)击>如一些人所指出的,在C典型的做法是让隐式转换照顾这。
的malloc(sizeof的为(int *))
意味着你离堆分配空间来存储一个指向 INT
。为指针,需要您预留的字节数。这将返回你应该强制转换为 A值INT **
。 (A指针指向一个 INT
)
为(int *)malloc的(的sizeof(INT))
是完全一样的第一个电话,但与结果明确铸造到一个指向 INT
。
请注意,在许多架构中,一个 INT
的大小为指针一样,所以这些会显得(错误地)是所有同样的事情。换句话说,你可以不小心做错事,并有导致code仍能正常工作。
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)) vs malloc(sizeof(int *)) vs (int *)malloc(sizeof(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*))
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))
is exactly the same as the first call, but with the the result explicitly casted to a pointer to an 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 *))对为(int *)malloc的(的sizeof(int)的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!