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

Calloc ในภาษา C

ความหมาย

calloc() จัดสรรหน่วยความจำแบบต่อเนื่อง (contiguous blocks) สำหรับ array และ initialize ค่าเป็น 0 อัตโนมัติ

Prototype

void *calloc(size_t nitems, size_t size);

ความแตกต่าง malloc vs calloc

คุณสมบัติmalloccalloc
พารามิเตอร์ขนาดรวม (bytes)จำนวน element, ขนาดต่อ element
ค่าเริ่มต้นGarbage (ไม่ initialize)0 (zero-initialized)
เหมาะสำหรับSingle block, structureArray, matrix
Overflow protectionไม่มีมี (nitems * size ต้องไม่ overflow)

Syntax

ptr = (cast*) calloc(n, sizeof(type));

ตัวอย่าง

int *ptr;
ptr = (int*) calloc(500, 2); // 500 blocks * 2 bytes = 1000 bytes
// หรือ
ptr = (int*) calloc(n, sizeof(int));

ตัวอย่างโปรแกรม: หาผลรวมเลขคู่และคี่

#include <stdio.h>
#include <stdlib.h>
int main() {
    int i, n;
    int *p;
    int even = 0, odd = 0;
    printf("ป้อนจำนวน elements: ");
    scanf("%d", &n);
    // จัดสรรหน่วยความจำด้วย calloc (initialize เป็น 0)
    p = (int*) calloc(n, sizeof(int));
    if (p == NULL) {
        printf("หน่วยความจำไม่พอ\\n");
        return 1;
    }
    printf("ป้อนตัวเลข %d ตัว:\\n", n);
    for (i = 0; i < n; i++) {
        scanf("%d", p + i);
    }
    for (i = 0; i < n; i++) {
        if (*(p + i) % 2 == 0)
            even += *(p + i);
        else
            odd += *(p + i);
    }
    printf("ผลรวมเลขคู่: %d\\n", even);
    printf("ผลรวมเลขคี่: %d\\n", odd);
    free(p);
    return 0;
}

ผลลัพธ์ตัวอย่าง

ป้อนจำนวน elements: 4
ป้อนตัวเลข 4 ตัว:
12 56 23 10
ผลรวมเลขคู่: 78
ผลรวมเลขคี่: 23

ข้อดีของ calloc

  • Initialize เป็น 0 อัตโนมัติ ป้องกัน garbage value
  • เหมาะสำหรับ array ที่ต้องเริ่มจาก 0
  • คำนวณขนาดรวมได้จาก n * size ลดโอกาสผิดพลาด
  • บางระบบ optimize calloc ให้เร็วกว่า malloc + memset

ข้อควรระวัง

  • ตรวจสอบค่า NULL เสมอ
  • free() เมื่อไม่ใช้แล้ว
  • size_t เป็น unsigned ใส่ค่าลบได้ (จะกลายเป็นค่ามากมาย)