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

เปรียบเทียบ calloc() และ malloc() ใน C

calloc()

จัดสรรหลายบล็อกขนาดเท่ากัน (contiguous location) เริ่มต้นค่าเป็น 0

ไวยากรณ์: void *calloc(size_t number, size_t size);

number: จำนวน elements, size: ขนาดแต่ละ element (bytes)

ตัวอย่าง calloc()

#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);
    return 0;
}

ผลลัพธ์

Enter elements of array: 2 24 35 12
Sum: 73

malloc()

จัดสรรหน่วยความจำขนาดที่ขอ คืน pointer ไป byte แรก ไม่ initialize ค่า (garbage)

ไวยากรณ์: pointer_name = (cast-type*) malloc(size);

ตัวอย่าง malloc()

#include <stdio.h>
#include <stdlib.h>
int main() {
    int n = 4, i, *p, s = 0;
    p = (int*) malloc(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);
    return 0;
}

ผลลัพธ์

Enter elements of array: 32 23 21 8
Sum: 84

ความแตกต่างหลัก: calloc() initialize 0 และจัดสรรเป็น array หลาย elements malloc() จัดสรร bytes เดียว ไม่ initialize