void *malloc(size_t size);
Parameter:
size: số byte cần cấp phát
Remark:
Hàm malloc( ) cấp phát vùng nhớ (các byte liên tiếp).
- Hàm trả về con trỏ tới vùng nhớ nếu thành công
- Hàm trả về NULL nếu không đủ vùng nhớ
Chú ý:
- Hàm malloc( ) có thể dùng để cấp phát vùng nhớ cho kiểu dữ liệu: mảng kí tự (char*), int*, struct,…
Ví dụ:
#include "stdio.h" #include "conio.h" #include "stdlib.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" ); } getch(); }
Kết quả:
Leave a Reply
You must be logged in to post a comment.