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); ใหม่()
ตัวดำเนินการใหม่ร้องขอการจัดสรรหน่วยความจำในฮีป หากมีหน่วยความจำเพียงพอ หน่วยความจำจะเริ่มต้นหน่วยความจำไปยังตัวแปรตัวชี้และส่งคืนที่อยู่
นี่คือไวยากรณ์ของตัวดำเนินการใหม่ในภาษา C++
pointer_variable = new datatype;
นี่คือไวยากรณ์ในการเริ่มต้นหน่วยความจำ
pointer_variable = new datatype(value);
นี่คือรูปแบบการจัดสรรบล็อกของหน่วยความจำ
pointer_variable = new datatype[size];
นี่คือตัวอย่างโอเปอเรเตอร์ใหม่ในภาษา C++
ตัวอย่าง
#include <iostream>
using namespace std;
int main () {
int *ptr1 = NULL;
ptr1 = new int;
float *ptr2 = new float(223.324);
int *ptr3 = new int[28];
*ptr1 = 28;
cout << "Value of pointer variable 1 : " << *ptr1 << endl;
cout << "Value of pointer variable 2 : " << *ptr2 << endl;
if (!ptr3)
cout << "Allocation of memory failed\n";
else {
for (int i = 10; i < 15; i++)
ptr3[i] = i+1;
cout << "Value to store in block of memory: ";
for (int i = 10; i < 15; i++)
cout << ptr3[i] << " ";
}
return 0;
} ผลลัพธ์
Value of pointer variable 1 : 28 Value of pointer variable 2 : 223.324 Value to store in block of memory: 11 12 13 14 15
ในโปรแกรมข้างต้น ตัวแปรตัวชี้สามตัวถูกประกาศเป็น ptr1, ptr2 และ ptr3 ตัวแปรพอยน์เตอร์ ptr1 และ ptr2 เริ่มต้นด้วยค่าโดยใช้ new() และ ptr3 จะจัดเก็บบล็อกที่จัดสรรของหน่วยความจำด้วยฟังก์ชัน new()
ptr1 = new int; float *ptr2 = new float(223.324); int *ptr3 = new int[28]; *ptr1 = 28;