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
395 views
in Technique[技术] by (71.8m points)

c - Is calloc(4, 6) the same as calloc(6, 4)?

I'm a beginner C programmer, and I assumed that this would be the case, but would like some affirmation if possible.

If they are the same, why not just take one argument instead?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

People mostly use allocation routines to allocate space for a set number of items, so calloc() allows that to be specified nicely. So, for example, if you want space for 100 integers or 20 of your own structure:

int *pInt = calloc (100, sizeof(int));
tMyStruct *pMyStruct = calloc (20, sizeof(tMyStruct));

This code actually looks slightly "nicer" than the equivalent malloc() calls:

int *pInt = malloc (100 * sizeof(int));
tMyStruct *pMyStruct = malloc (20 * sizeof(tMyStruct));

although, to seasoned C coders, there's no real distinction (other than the zero initialization of course).

I have to say I have never used calloc in the wild, since I'm almost always creating a struct where zero's don't make sense. I prefer to initialize all the fields manually to ensure I get the values I want.


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

1.4m articles

1.4m replys

5 comments

56.9k users

...