malloc()
malloc() 함수는 요청된 바이트 크기를 할당하는 데 사용되며 할당된 메모리의 첫 번째 바이트에 대한 포인터를 반환합니다. 실패하면 null 포인터를 반환합니다.
다음은 C++ 언어의 malloc() 구문입니다.
pointer_name = (cast-type*) malloc(size);
여기,
pointer_name − 포인터에 부여된 모든 이름.
캐스트 유형 − malloc()에 의해 할당된 메모리를 캐스팅하려는 데이터 유형.
크기 − 할당된 메모리의 크기(바이트)입니다.
다음은 C 언어의 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
위의 프로그램에서는 4개의 변수가 선언되었고 그 중 하나는 malloc에 의해 할당된 메모리를 저장하는 포인터 변수 *p입니다. 요소의 합계를 출력하고 있습니다.
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); 새로운()
new 연산자는 힙에 메모리 할당을 요청합니다. 사용 가능한 메모리가 충분하면 포인터 변수에 메모리를 초기화하고 해당 주소를 반환합니다.
다음은 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;