malloc()
จัดสรรหน่วยความจำขนาดที่ขอ คืน pointer ไป byte แรก ไม่ initialize ค่า คืน NULL ถ้าล้มเหลว
ไวยากรณ์: 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
new()
Operator ใหม่ใน C++ ขอหน่วยความจำใน heap ถ้าพอ จะ initialize และคืน address
ไวยากรณ์:pointer_variable = new datatype;pointer_variable = new datatype(value); (initialize)pointer_variable = new datatype[size]; (array)
ตัวอย่าง new()
#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
ความแตกต่าง: malloc() เป็น C library function ต้อง cast, ไม่ initialize, คืน void*
new() เป็น C++ operator รู้ type เอง, สามารถ initialize ได้, คืน typed pointer, throw exception ถ้า fail