Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> C Language

calloc() in C: Zero‑Initialized Memory Allocation and a Practical Example

What is calloc in C?

The calloc() function in C allocates multiple blocks of memory of equal size and initializes every byte to zero. It’s a dynamic allocation routine used for complex data structures like arrays or structs, returning a void * pointer.

While malloc() reserves a single contiguous block, calloc() requests n blocks, each of size bytes, guaranteeing they’re zeroed and contiguous.

Syntax

ptr = (cast_type *)calloc(n, size);

Using calloc – A Sample Program

The following program demonstrates how calloc() can be used to compute the sum of the first ten terms of an arithmetic sequence.

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

int main(void) {
    int *ptr, sum = 0;

    ptr = calloc(10, sizeof(int));
    if (!ptr) {
        fprintf(stderr, "Error! Memory not allocated.\n");
        return EXIT_FAILURE;
    }

    printf("Calculating the sum of the first 10 terms:\n");
    for (int i = 0; i < 10; ++i) {
        ptr[i] = i;
        sum += ptr[i];
    }

    printf("Sum = %d\n", sum);
    free(ptr);
    return EXIT_SUCCESS;
}

Output

Calculating the sum of the first 10 terms:
Sum = 45

C Language

  1. Mastering C++ Vectors: Dynamic Arrays, Iterators, and Practical Examples
  2. C++ Polymorphism Explained: Practical Examples & Key Concepts
  3. C++ Functions Explained with Practical Code Examples
  4. C Hello World: Your First Program – A Step‑by‑Step Guide
  5. Master C Functions: Practical Examples of Recursion & Inline Techniques
  6. malloc vs calloc: Key Differences Explained with Practical Examples
  7. Dynamic Memory Allocation in C: Understanding malloc() with Practical Examples
  8. Using realloc() in C: Syntax, Best Practices & Example
  9. Mastering C’s free() Function: Practical Guide & Example
  10. Mastering Python’s strip() Method: Comprehensive Guide & Practical Examples