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

Compile-time vs Run-time Array Initialization ในภาษา C


Compile-time Initialization (Static)

กำหนดค่าใน Code ตอนเขียนโปรแกรม


// 1D Array
int arr[5] = {1, 2, 3, 4, 5};
float prices[3] = {10.5, 20.0, 15.75};
char name[10] = {'H', 'e', 'l', 'l', 'o', '\0'};
// หรือ
char name[] = "Hello"; // Auto size + Null terminator

// 2D Array
int matrix[2][3] = {{1,2,3}, {4,5,6}};

Run-time Initialization (Dynamic)

รับค่าจาก User หรือคำนวณระหว่าง Run


// 1D Array
int n, arr[100];
printf("Enter size: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
    printf("arr[%d]: ", i);
    scanf("%d", &arr[i]);
}

// 2D Array (VLA - C99)
int rows, cols;
scanf("%d %d", &rows, &cols);
int matrix[rows][cols];
for (int i = 0; i < rows; i++)
    for (int j = 0; j < cols; j++)
        scanf("%d", &matrix[i][j]);

ตัวอย่างโปรแกรม: Compile-time

#include <stdio.h>
int main() {
    int arr[5] = {10, 20, 30, 40, 50};
    printf("Compile-time initialized array:\n");
    for (int i = 0; i < 5; i++)
        printf("%d ", arr[i]);
    return 0;
}

Output: 10 20 30 40 50

ตัวอย่างโปรแกรม: Run-time (2D Array Sum/Product)

#include <stdio.h>

int main() {
    int rows = 2, cols = 3;
    int A[rows][cols], B[rows][cols];
    int sum[rows][cols], product[rows][cols];
    
    printf("Matrix A:\n");
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++) {
            printf("A[%d][%d]: ", i, j);
            scanf("%d", &A[i][j]);
        }
    
    printf("Matrix B:\n");
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++) {
            printf("B[%d][%d]: ", i, j);
            scanf("%d", &B[i][j]);
        }
    
    printf("\nSum:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            sum[i][j] = A[i][j] + B[i][j];
            printf("%d\t", sum[i][j]);
        }
        printf("\n");
    }
    
    printf("\nProduct:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            product[i][j] = A[i][j] * B[i][j];
            printf("%d\t", product[i][j]);
        }
        printf("\n");
    }
    return 0;
}

เปรียบเทียบ

คุณสมบัติCompile-timeRun-time
Flexibilityต่ำ (Hard-coded)สูง (User Input)
MemoryStack (Fixed)Stack (VLA) / Heap (Malloc)
Performanceเร็วกว่า (Compile-time)ช้ากว่าเล็กน้อย
ใช้เมื่อข้อมูลคงที่, Lookup Tablesข้อมูลจาก User, File, Network

Dynamic Allocation (Heap) - ทางเลือกที่ 3


int **arr = malloc(rows * sizeof(int *));
for (int i = 0; i < rows; i++)
    arr[i] = malloc(cols * sizeof(int));
// ใช้ arr[i][j] ได้เหมือนปกติ
// ต้อง free() ทีละ Row แล้วค่อย free(arr)