calloc()
ฟังก์ชัน calloc() ย่อมาจากตำแหน่งที่อยู่ติดกัน มันทำงานคล้ายกับ malloc() แต่จัดสรรบล็อกหน่วยความจำหลายบล็อกที่มีขนาดเท่ากัน
นี่คือไวยากรณ์ของ calloc() ในภาษา C
void *calloc(size_t number, size_t size);
ที่นี่
หมายเลข − จำนวนองค์ประกอบของอาร์เรย์ที่จะจัดสรร
ขนาด − ขนาดของหน่วยความจำที่จัดสรรเป็นไบต์
นี่คือตัวอย่าง calloc() ในภาษา C
ตัวอย่าง
#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
ในโปรแกรมข้างต้น บล็อกหน่วยความจำจะถูกจัดสรรโดย calloc() ถ้าตัวแปรตัวชี้เป็นค่าว่าง จะไม่มีการจัดสรรหน่วยความจำ หากตัวแปรพอยน์เตอร์ไม่เป็นค่าว่าง ผู้ใช้ต้องป้อนองค์ประกอบสี่รายการของอาร์เรย์ จากนั้นจึงคำนวณผลรวมขององค์ประกอบ
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);
} malloc()
ฟังก์ชัน malloc() ใช้เพื่อจัดสรรขนาดไบต์ที่ร้องขอ และส่งคืนตัวชี้ไปยังไบต์แรกของหน่วยความจำที่จัดสรร ส่งคืนตัวชี้ null หากล้มเหลว
นี่คือไวยากรณ์ของ malloc() ในภาษา C
pointer_name = (cast-type*) malloc(size);
ที่นี่
ชื่อตัวชี้ − ชื่อใดๆ ที่กำหนดให้กับตัวชี้
ประเภทนักแสดง − ประเภทข้อมูลที่คุณต้องการส่งหน่วยความจำที่จัดสรรโดย malloc()
ขนาด − ขนาดของหน่วยความจำที่จัดสรรเป็นไบต์
นี่คือตัวอย่างของ malloc() ในภาษา C
ตัวอย่าง
#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
ในโปรแกรมข้างต้น มีการประกาศตัวแปรสี่ตัวและหนึ่งในนั้นคือตัวแปรตัวชี้ *p ซึ่งจัดเก็บหน่วยความจำที่จัดสรรโดย malloc ผู้ใช้พิมพ์องค์ประกอบของอาร์เรย์และพิมพ์ผลรวมขององค์ประกอบ
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);