C 语言为内存的分配和管理提供了几个函数,这些函数可以在
动态分配内存
#include <stdio.h>#include <stdlib.h>#include <string.h>int main(){char name[100];char *description;strcpy(name, "Zara Ali");/* 动态分配内存 */description = malloc( 200 * sizeof(char) );if( description == NULL ){fprintf(stderr, "Error - unable to allocate required memory\n");}else{strcpy( description, "Zara ali a DPS student in class 10th");}printf("Name = %s\n", name );printf("Description: %s\n", description );}
上面的程序也可以使用calloc()来编写,只需要把malloc替换成calloc即可,如下所示:
calloc(200, sizeof(char));
当动态分配内存时,您有完全控制权,可以传递任何大小的值。而那些预先定义了大小的数组,一旦定义则无法改变大小。
重新调整内存的大小和释放内存
当程序退出时,操作系统会自动释放所有分配给程序的内存,但是,建议您在不需要内存时,都应该调用函数 free() 来释放内存。或者,您可以通过调用函数 realloc() 来增加或减少已分配的内存块的大小。让我们使用 realloc() 和 free() 函数,再次查看上面的实例:
#include <stdio.h>#include <stdlib.h>#include <string.h>int main(){char name[100];char *description;strcpy(name, "Zara Ali");/* 动态分配内存 */description = malloc( 30 * sizeof(char) );if( description == NULL ){fprintf(stderr, "Error - unable to allocate required memory\n");}else{strcpy( description, "Zara ali a DPS student.");}/* 假设您想要存储更大的描述信息 */description = realloc( description, 100 * sizeof(char) );if( description == NULL ){fprintf(stderr, "Error - unable to allocate required memory\n");}else{strcat( description, "She is in class 10th");}printf("Name = %s\n", name );printf("Description: %s\n", description );/* 使用 free() 函数释放内存 */free(description);}
