Memory Allocation with the calloc() Function - C Memory

C examples for Memory:calloc

Introduction

The calloc() function can allocate memory as a number of elements of a given size. It initializes the memory allocated to zero.

The calloc() function requires two argument values:

• the number of data items for which space is required
• the size of each data item.

Both arguments are expected to be of type size_t.

The following code uses calloc() to allocate memory for an array of 75 elements of type int:

int *pNumber = (int*) calloc(75, sizeof(int));

The following code shows how to use calloc() method.

Demo Code

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

int main(void)
{
unsigned long long *pPrimes = NULL;  // Pointer to primes storage area
unsigned long long trial = 0;        // Integer to be tested
bool found = false;                  // Indicates when we find a prime
int total = 0;                       // Number of primes required
int count = 0;                       // Number of primes found

total = 6;/*  w  w  w. j  ava 2  s.c o m*/

pPrimes = (unsigned long long *)calloc((size_t)total, sizeof(unsigned long long));
if (pPrimes == NULL) {
printf("Not enough memory. It's the end I'm afraid.\n");
return 1;
}

*pPrimes = 2ULL;                     // First prime
*(pPrimes + 1) = 3ULL;               // Second prime
*(pPrimes + 2) = 5ULL;               // Third prime
count = 3;                           // Number of primes stored
trial = 5ULL;                        // Set to the last prime we have

// Find all the primes required
while (count < total)
{
trial += 2ULL;                     // Next value for checking

// Divide by the primes we have. If any divide exactly - it's not prime
for (int i = 1; i < count; ++i)
{
if (!(found = (trial % *(pPrimes + i))))
break;                         // Exit if zero remainder
}

if (found)                          // We got one - if found is true
*(pPrimes + count++) = trial;    // Store it and increment count
}
for (int i = 0; i < total; ++i) {
printf("%12llu", *(pPrimes + i));
if (!((i + 1) % 5))
printf("\n");                   // Newline after every 5
}
printf("\n");                       // Newline for any stragglers

free(pPrimes);
pPrimes = NULL;
return 0;
}

Result 