English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
This functionmalloc()
used to allocate the requested byte size and return a pointer to the first byte of the allocated memory. If it fails, it returns a null pointer.
This ismalloc()
C ++language syntax,
pointer_name = (cast-type*) malloc(size);
Here,
pointer_name-to any name for the pointer.
cast- type-You need to cast the data type of the allocated memorymalloc()
.
Size-the size of memory allocated in bytes.
This ismalloc()
C language example,
#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; }
This is the output,
Enter elements of array : 32 23 21 8 Sum : 84
In the above program, four variables are declared, one of which is a pointer variable* p, it stores the memory allocated by malloc. We are printing the sum of the elements.
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);
The new operator requests memory allocation on the heap. If there is enough memory available, it initializes the memory to a pointer variable and returns its address.
This is C ++The syntax of the new operator in the language,
pointer_variable = new datatype;
This is the syntax of initializing memory,
pointer_variable = new datatype(value);
This is the syntax of allocating a memory block,
pointer_variable = new datatype[size];
This is C ++of the new operator in a language,
#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; }
Output result
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
In the above program, three pointer variables are declared as ptr1, ptr2and ptr3. The pointer variable ptr1and ptr2using value initialization,new()
and ptr3Bynew()
Method stores the allocated memory block.
ptr1 = new int; float *ptr2 = new float(223.324); int *ptr3 = new int[28]; *ptr1 = 28;