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

ฟังก์ชัน malloc() จัดสรรหน่วยความจำไดนามิกใน C


โจทย์

เขียนโปรแกรม C แสดงและบวกค่าอาร์เรย์โดยใช้ Dynamic Memory Allocation (malloc)

malloc() - Memory Allocation

  • จัดสรรหน่วยความจำขนาดระบุ (bytes) ตอน Run-time
  • คืนค่า void pointer (ต้อง cast)
  • ไม่ทำการ initialize ค่า (ค่าขยะ/garbage)
  • คืนค่า NULL ถ้าจัดสรรไม่สำเร็จ

Syntax

void *malloc(size_t size);

ตัวอย่าง

int *ptr = (int*)malloc(1000);           // จอง 1000 bytes
int *ptr = (int*)malloc(n * sizeof(int)); // จองสำหรับ n integers

โปรแกรมตัวอย่าง: รับจำนวนสมาชิก จองหน่วยความจำ รับค่า และหาผลรวม

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

int main() {
    int n, i, sum = 0;
    int *p;
    
    printf("Enter number of elements: ");
    scanf("%d", &n);
    
    p = (int*)malloc(n * sizeof(int));
    if (p == NULL) {
        printf("Memory not available\n");
        return 1;
    }
    
    printf("Enter elements:\n");
    for(i = 0; i < n; i++) {
        scanf("%d", p + i);
        sum += *(p + i);
    }
    
    printf("Sum = %d\n", sum);
    
    free(p);  // ปล่อยหน่วยความจำ
    
    // หลัง free ค่าจะเป็น garbage
    printf("After free (garbage values):\n");
    for(i = 0; i < n; i++) printf("%d\n", p[i]);
    
    return 0;
}

ผลลัพธ์

Enter number of elements: 5
Enter elements: 23 45 65 12 23
Sum = 168
After free (garbage values):
10753152
0
10748240
0
23