[ First ]  [ Previous ]  [ Next ]  [ Last ]  [ Manuals ]


calloc

Allocate space for a group of objects.

Compatibility:

This function is compatible with the following targets:

ANSI

BeOS

EMB/RTOS

Mac OS

Palm OS

Win32


Prototype:
#include <stdlib.h>
void *calloc(size_t nmemb, size_t elemsize);
Parameters:

Parameters for this facility are:

nmemb  
size_t  
Number of elements  
elemsize  
size_t  
The size of the elements  

Remarks:

The calloc() function allocates contiguous space for nmemb elements of size elemsize. The space is initialized with all bits zero.

Return:

calloc() returns a pointer to the first byte of the memory area allocated. calloc() returns a null pointer (NULL) if no space could be allocated.

See Also:

"vec_calloc"

"malloc"

"realloc"

Example of calloc() usage.:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
	static char s[] = "Metrowerks compilers";
	char *sptr1, *sptr2, *sptr3;

	// allocate the memory three different ways
	// one: allocate a thirty byte block of
	//	uninitialized memory
	sptr1 = (char *) malloc(30);
	strcpy(sptr1, s);
	printf("Address of sptr1: %p\n", sptr1);

	// two: allocate twenty bytes of unitialized memory
	sptr2 = (char *) malloc(20);
	printf("sptr2 before reallocation: %p\n", sptr2);
	strcpy(sptr2, s);
	// now re-allocate ten extra bytes (for a total of
	// thirty bytes)
	//
	// note that the memory block pointed to by sptr2 is
	// still contiguous after the call to realloc()
	sptr2 = (char *) realloc(sptr2, 30);
	printf("sptr2 after reallocation: %p\n", sptr2);

	// three: allocate thirty bytes of initialized memory
	sptr3 = (char *) calloc(strlen(s), sizeof(char));
	strcpy(sptr3, s);
	printf("Address of sptr3: %p\n", sptr3);

	puts(sptr1);
	puts(sptr2);
	puts(sptr3);

	// release the allocated memory to the heap
	free(sptr1);
	free(sptr2);
	free(sptr3);

	return 0;
}

Output:
Address of sptr1: 5e5432
sptr2 before reallocation: 5e5452
sptr2 after reallocation: 5e5468
Address of sptr3: 5e5488
Metrowerks compilers
Metrowerks compilers
Metrowerks compilers


[ First ]  [ Previous ]  [ Next ]  [ Last ]  [ Manuals ]

Visit the Metrowerks website at: http://www.metrowerks.com
For assistance contact Metrowerks Technical Support at: cw_support@metrowerks.com
Copyright © 2000, Metrowerks Corp. All rights reserved.

Last updated: August 16, 2000