Cover Image for Calloc in C
67 views

Calloc in C

The calloc() function is used to allocate and initialize memory for an array of elements. It stands for “contiguous allocation,” and it is similar to the malloc() function but with the added capability of initializing the allocated memory to zero. The calloc() function is part of the C Standard Library and is declared in the <stdlib.h> header.

Here’s the syntax of the calloc() function:

C
void *calloc(size_t num_elements, size_t element_size);
  • num_elements: The number of elements you want to allocate memory for.
  • element_size: The size (in bytes) of each element.

The calloc() function returns a pointer to the first byte of the allocated memory block. If the allocation fails (e.g., due to insufficient memory), it returns a NULL pointer.

Here’s an example of how to use the calloc() function to allocate memory for an integer array and initialize it with zeros:

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

int main() {
    int num_elements = 5;

    // Allocate memory for an integer array of size 5
    int *arr = (int *)calloc(num_elements, sizeof(int));

    if (arr == NULL) {
        printf("Memory allocation failed.\n");
        return 1; // Exit with an error code
    }

    // Initialize the array with zeros
    for (int i = 0; i < num_elements; i++) {
        arr[i] = 0;
    }

    // Print the array
    printf("Array elements: ");
    for (int i = 0; i < num_elements; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    // Free the allocated memory
    free(arr);

    return 0;
}

In this example:

  1. We include the <stdio.h> and <stdlib.h> headers to use the necessary functions and data types.
  2. We allocate memory for an integer array of size 5 using calloc(5, sizeof(int)).
  3. We check if the allocation was successful (i.e., arr is not NULL).
  4. We initialize the array with zeros using a loop.
  5. We print the array elements to verify that they are initialized to zero.
  6. Finally, we free the allocated memory using the free() function to prevent memory leaks.

The calloc() function is particularly useful when you need to allocate memory for arrays or data structures that should be initialized to a specific value, such as zero.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS