English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In the C language, void pointers are implicitly converted to object pointer types. This functionmalloc()
In C89the standard returns void *. In earlier versions of Cmalloc()
Returns char *. In C ++In the language, by defaultmalloc()
Returns an int value. Therefore, use explicit conversion to convert the pointer to an object pointer.
The following is the syntax for allocating memory in C language.
pointer_name = malloc(size);
Here,
pointer_name-to any name given to the pointer.
Size-the size of memory allocated in bytes.
The following ismalloc()
C language example.
#include <stdio.h> #include <stdlib.h> int main() { int n = 4, i, *p, s = 0; p = 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; }
Output result
Enter elements of array : 2 28 12 32 Sum : 74
In the above C language example, if we perform an explicit cast, no error will be displayed.
The following is using C ++the syntax for allocating memory in the language.
pointer_name = (cast-type*) malloc(size);
Here,
pointer_name-to any name given to the pointer.
cast- type-to the data type that needs to be converted to allocate memory by forcemalloc()
.
Size-the size of memory allocated in bytes.
The following ismalloc()
C ++language examples.
#include <iostream> using namespace std; int main() { int n = 4, i, *p, s = 0; p = (int *)malloc(n * sizeof(int)); if(p == NULL) { cout << "\nError! memory not allocated."; exit(0); } cout << "\nEnter elements of array : "; for(i = 0; i < n; ++i) { cin >> (p + i); s += *(p + i); } cout << "\nSum : ", s; return 0; }
Output result
Enter elements of array : 28 65 3 8 Sum : 104
In the above C ++In the language examples, if we do not perform an explicit conversion, the program will display the following error.
error: invalid conversion from ‘void*’ to ‘int*’ [-fpermissive] p = malloc(n * sizeof(int));