English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
the functioncalloc()
representing consecutive positions. It works similarly tomalloc()
but it allocates multiple memory blocks of the same size.
This iscalloc()
C language syntax,
void *calloc(size_t number, size_t size);
Here,
numberthe number of elements of the array to be allocated- .
Size-the size of memory allocated in bytes.
This iscalloc()
C language example,
#include <stdio.h> #include <stdlib.h> int main() { int n = 4, i, *p, s = 0; p = (int*) calloc(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 24 35 12 Sum: 73
In the above program, the memory block is allocatedcalloc()
. If the pointer variable is NULL, no memory allocation is made. If the pointer variable is not NULL, the user must enter four elements of the array, and then calculate the sum of the elements.
p = (int*) calloc(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); }
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 memory tomalloc()
.
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,
Output result
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. The elements of the array are printed by the user, and the sum of the elements is printed.
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);