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

การจัดสรรหน่วยความจำแบบคงที่ (Static Memory Allocation) ใน C


หน่วยความจำจัดสรรได้ 2 แบบ: Static (คงที่) และ Dynamic (ไดนามิก)

การจัดสรรหน่วยความจำแบบคงที่ (Static Memory Allocation) ใน C

Static Memory Allocation

  • จัดสรรพื้นที่ขนาดคงที่ ในขั้นตอนคอมไพล์ (Compile-time)
  • ไม่สามารถเปลี่ยนขนาดได้ระหว่างรันโปรแกรม
  • ใช้ Stack ในการจัดการ
  • หน่วยความจำจะถูกปล่อยอัตโนมัติเมื่อจบ Scope
  • มีประสิทธิภาพน้อยกว่า Dynamic สำหรับข้อมูลขนาดไม่แน่นอน

ตัวอย่างที่ 1: Array แบบ Static

#include <stdio.h>
int main() {
    int a[5] = {10, 20, 30, 40, 50};
    int i;
    printf("Array elements: ");
    for(i = 0; i < 5; i++) printf("%d ", a[i]);
    return 0;
}

ผลลัพธ์

Array elements: 10 20 30 40 50

ตัวอย่างที่ 2: คำนวณผลรวมและผลคูณของ Array

#include <stdio.h>
int main() {
    int array[5] = {10, 20, 30, 40, 50};
    int i, sum = 0, product = 1;
    
    for(i = 0; i < 5; i++) {
        sum += array[i];
        product *= array[i];
    }
    
    printf("Sum: %d\n", sum);        // 150
    printf("Product: %d\n", product); // 12000000
    return 0;
}