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

ฟังก์ชัน malloc ในภาษา C คืออะไร


ฟังก์ชัน malloc() ย่อมาจาก memory allocation คือการจัดสรรหน่วยความจำแบบไดนามิก

จองพื้นที่หน่วยความจำตามขนาดที่ระบุ และส่งคืนพอยน์เตอร์ null ที่ชี้ไปยังตำแหน่งหน่วยความจำ

malloc() ส่งคืนค่าขยะ (Garbage Value) พอยน์เตอร์ที่ส่งคืนเป็นชนิด void

ไวยากรณ์สำหรับฟังก์ชัน malloc():

ptr = (castType*) malloc(size);

ตัวอย่าง

ตัวอย่างต่อไปนี้แสดงการใช้งานฟังก์ชัน malloc():

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    char *MemoryAlloc;
    
    /* จัดสรรหน่วยความจำแบบไดนามิก */
    MemoryAlloc = malloc(15 * sizeof(char));
    
    if(MemoryAlloc == NULL) {
        printf("Couldn't able to allocate requested memory\n");
    } else {
        strcpy(MemoryAlloc, "TutorialsPoint");
    }
    
    printf("Dynamically allocated memory content : %s\n", MemoryAlloc);
    free(MemoryAlloc);
    return 0;
}

ผลลัพธ์

เมื่อรันโปรแกรม จะได้ผลลัพธ์ดังนี้:

Dynamically allocated memory content: TutorialsPoint