calloc in cpp code example
Example 1: calloc in C++/C
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
int *ptr;
ptr = (int *)calloc(5, sizeof(int));
if (!ptr) {
cout << "Memory Allocation Failed";
exit(1);
}
cout << "Initializing values..." << endl
<< endl;
for (int i = 0; i < 5; i++) {
ptr[i] = i * 2 + 1;
}
cout << "Initialized values" << endl;
for (int i = 0; i < 5; i++) {
cout << *(ptr + i) << endl;
}
free(ptr);
return 0;
}
Example 2: Calloc C++
void* calloc (size_t num, size_t size);
Example 3: Calloc C++
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i,n;
int * pData;
printf ("Amount of numbers to be entered: ");
scanf ("%d",&i);
pData = (int*) calloc (i,sizeof(int));
if (pData==NULL) exit (1);
for (n=0;n<i;n++)
{
printf ("Enter number #%d: ",n+1);
scanf ("%d",&pData[n]);
}
printf ("You have entered: ");
for (n=0;n<i;n++) printf ("%d ",pData[n]);
free (pData);
return 0;
}