calloc c example

Example 1: malloc in c

#include <stdlib.h>

void *malloc(size_t size);

void exemple(void)
{
  char *string;
  
  string = malloc(sizeof(char) * 5);
  if (string == NULL)
    return;
  string[0] = 'H';
  string[1] = 'e';
  string[2] = 'y';
  string[3] = '!';
  string[4] = '\0';
  printf("%s\n", string);
  free(string);
}

/// output : "Hey!"

Example 2: c calloc

// The Malloc way
void *ptr = malloc(sizeof(Type) * n_elem);
// The Calloc way
void *ptr = calloc(n_elem, sizeof(Type));

Example 3: c calloc

void *calloc(size_t nitems, size_t size)

Tags:

Cpp Example