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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…