Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

c - 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))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 int *. (A pointer to an int.) As some have noted, typical practice in C is to let implicit casting take care of this.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...