第1个回答 2011-11-28
1.malloc 的格式:void *malloc( size_t size );返回的是一个空的指针所以应用时:
定义一个:int * a分配n个字节的空间:a = (int*)malloc(n);//一定要进行强制类型转换,你定义的说什么类型就强制转换成什么类型的。
2.calloc 的格式:void *calloc( size_t num, size_t size );参数1 num :Number of elements
参数2 size :Length in bytes of each element;
Example
/* CALLOC.C: This program uses calloc to allocate space for
* 40 long integers. It initializes each element to zero.
*/
#include <stdio.h>
#include <malloc.h>
void main( void )
{
long *buffer;
buffer = (long *)calloc( 40, sizeof( long ) );
if( buffer != NULL )
printf( "Allocated 40 long integers\n" );
else
printf( "Can't allocate memory\n" );
free( buffer );
}
Output
Allocated 40 long integers
3.void *realloc( void *memblock, size_t size );
Example
/* REALLOC.C: This program allocates a block of memory for
* buffer and then uses _msize to display the size of that
* block. Next, it uses realloc to expand the amount of
* memory used by buffer and then calls _msize again to
* display the new amount of memory allocated to buffer.
*/
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
void main( void )
{
long *buffer;
size_t size;
if( (buffer = (long *)malloc( 1000 * sizeof( long ) )) == NULL )
exit( 1 );
size = _msize( buffer );
printf( "Size of block after malloc of 1000 longs: %u\n", size );
/* Reallocate and show new size: */
if( (buffer = (long *)realloc( buffer, size + (1000 * sizeof( long )) ))
== NULL )
exit( 1 );
size = _msize( buffer );
printf( "Size of block after realloc of 1000 more longs: %u\n",
size );
free( buffer );
exit( 0 );
}
Output
Size of block after malloc of 1000 longs: 4000
Size of block after realloc of 1000 more longs: 8000
4.void free( void *memblock );
Example
/* MALLOC.C: This program allocates memory with
* malloc, then frees the memory with free.
*/
#include <stdlib.h> /* For _MAX_PATH definition */
#include <stdio.h>
#include <malloc.h>
void main( void )
{
char *string;
/* Allocate space for a path name */
string = (char *)malloc( _MAX_PATH );
if( string == NULL )
printf( "Insufficient memory available\n" );
else
{
printf( "Memory space allocated for path name\n" );
free( string );
printf( "Memory freed\n" );
}
}
Output
Memory space allocated for path name
Memory freed
第2个回答 2011-11-27
一般申请大的内存时使用:
char *string;
string = (char *)malloc(256); //申请256字节的字符串
free(string); //用完后记得释放内存
=======
string = (char *)malloc(128);
str = realloc(string, 256); //128太小,重新申请256大小。
这些用法可以搜索“C库函数大全”,里面有各种库函数的详细用法和举例