malloc函數
- 原型:extern void* malloc(unsigned int size);
- 功能:動態分配內存;
- 注意:size僅僅爲申請內存字節大小,與申請內存塊中存儲的數據類型無關,故編程時需要通過以下方式給出:"長度 * sizeof(數據類型)";
//動態分配內存,輸入5個數據,並把低於60的值打印出來
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr = (int *)malloc(5 * sizeof(int));//分配內存
for (int i = 0; i < 5; i++)
{
scanf_s("%d", &ptr[i]);//輸入數據
}
int min = 60;
for (int i = 0; i < 5; i++)
{
if (min > *(ptr + i))
printf("%5d", *(ptr + i));//打印出低於60的值
}
free(ptr);
system("pause");
return 0;
}
free函數
- 原型:void free(void * ptr);
- 功能:搭配malloc()函數,釋放malloc函數申請的動態內存;
- 注意:對於free(ptr),若ptr爲NULL,則可進行多次釋放,若ptr是非空指針,則free對ptr只能進行一次操作,否則程序將崩潰;
- 示例:見malloc函數;
- 結果:見malloc函數;
realloc函數
- 原型: void realloc(void ptr,unsigned int size);
- 功能:先判斷當前指針是否有足夠的連續空間,若足夠,擴大ptr指向的地址並返回,若不夠,怎按size指定的大小分配空間,將原數據copy到新分配的內存中,然後釋放原ptr所指向區域;
- 注意:內存使用完畢後,應使用free()函數釋放,但原來的指針是自動釋放,不需要使用free;
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *str;
/* 一開始的內存分配 */
str = (char *)malloc(15);
strcpy(str, "Hello World!");
printf("String = %s\n", str);
/* 重新分配內存 */
str = (char *)realloc(str, 25);
strcat(str, ", C");
printf("String = %s\n", str);
free(str);
system("pause");
return 0;
}
calloc函數
- 原型:void* calloc(unsigned int num,unsigned int size);
- 功能:爲已經分配的內存重新分配空間並複製內容;
- 注意:num:對象個數,size:對象佔據的內存字節數,相較於malloc函數,calloc函數會自動將內存初始化爲0;
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
int i;
int *ptr;
printf("元素個數爲:");
scanf("%d", &num);
ptr = (int*)calloc(num, sizeof(int));
printf("輸入 %d 個數字:\n", num);
for (i = 0; i < num; i++)
{
scanf("%d", &ptr[i]);
}
printf("輸入的數字爲:");
for (i = 0; i < num; i++) {
printf("%d ", ptr[i]);
}
printf("\n");
system("pause");
return 0;
}