Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

Dynamic Memory Allocation ใน C

C จัดสรรหน่วยความจำ Dynamic ด้วยฟังก์ชันใน <stdlib.h>:

FunctionDescription
calloc(num, size)จัดสรร Array num องค์ประกอบ ขนาด size bytes เริ่มต้นเป็น 0
free(ptr)ปล่อยหน่วยความจำที่ ptr ชี้
malloc(num)จัดสรร num bytes ไม่ Initialize
realloc(ptr, newsize)ปรับขนาดหน่วยความจำที่ ptr ชี้

ตัวอย่าง malloc/free

char *desc = malloc(200 * sizeof(char));
if (desc) strcpy(desc, "Description");
free(desc);

ตัวอย่าง realloc

desc = malloc(30);
strcpy(desc, "Short");
desc = realloc(desc, 100);
strcat(desc, " Longer");
free(desc);