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

การใช้ realloc() ใน C

realloc() ปรับขนาดบล็อกหน่วยความจำที่จัดสรรด้วย malloc หรือ calloc แล้ว

ไวยากรณ์

void *realloc(void *pointer, size_t size)

pointer: pointer ไปบล็อกเก่า, size: ขนาดใหม่ (bytes)

ตัวอย่าง

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

int main() {
    int n = 4, i, *p, s = 0;
    p = (int*) calloc(n, sizeof(int));
    if(p == NULL) {
        printf("\nError! memory not allocated.");
        exit(0);
    }
    printf("\nEnter elements of array: ");
    for(i = 0; i < n; ++i) {
        scanf("%d", p + i);
        s += *(p + i);
    }
    printf("\nSum: %d", s);
    p = (int*) realloc(p, 6 * sizeof(int)); // ขยายเป็น 6 int
    printf("\nEnter elements of array: ");
    for(i = 0; i < 6; ++i) { // หมายเหตุ: ต้อง loop 6 รอบ
        scanf("%d", p + i);
        s += *(p + i);
    }
    printf("\nSum: %d", s);
    return 0;
}

ผลลัพธ์

Enter elements of array: 3 34 28 8
Sum: 73
Enter elements of array: 3 28 33 8 10 15
Sum: 145

จัดสรรหน่วยความจำด้วย calloc() คำนวณผลรวม แล้ว realloc() ขยายจาก 4 เป็น 6 elements คำนวณผลรวมใหม่