allocate heap in c code code example

Example 1: heapify in c

// Max-Heap data structure in C

#include <stdio.h>
int size = 0;
void swap(int *a, int *b)
{
  int temp = *b;
  *b = *a;
  *a = temp;
}
void heapify(int array[], int size, int i)
{
  if (size == 1)
  {
    printf("Single element in the heap");
  }
  else
  {
    int largest = i;
    int l = 2 * i + 1;
    int r = 2 * i + 2;
    if (l < size && array[l] > array[largest])
      largest = l;
    if (r < size && array[r] > array[largest])
      largest = r;
    if (largest != i)
    {
      swap(&array[i], &array[largest]);
      heapify(array, size, largest);
    }
  }
}
void insert(int array[], int newNum)
{
  if (size == 0)
  {
    array[0] = newNum;
    size += 1;
  }
  else
  {
    array[size] = newNum;
    size += 1;
    for (int i = size / 2 - 1; i >= 0; i--)
    {
      heapify(array, size, i);
    }
  }
}
void deleteRoot(int array[], int num)
{
  int i;
  for (i = 0; i < size; i++)
  {
    if (num == array[i])
      break;
  }

  swap(&array[i], &array[size - 1]);
  size -= 1;
  for (int i = size / 2 - 1; i >= 0; i--)
  {
    heapify(array, size, i);
  }
}
void printArray(int array[], int size)
{
  for (int i = 0; i < size; ++i)
    printf("%d ", array[i]);
  printf("\n");
}
int main()
{
  int array[10];

  insert(array, 3);
  insert(array, 4);
  insert(array, 9);
  insert(array, 5);
  insert(array, 2);

  printf("Max-Heap array: ");
  printArray(array, size);

  deleteRoot(array, 4);

  printf("After deleting an element: ");

  printArray(array, size);
}

Example 2: how to allocate on heap in c++

#include <iostream>
#include <string>

using String = std::string;
class Entity
{
private:
	String m_Name;
public:
	Entity() : m_Name("Unknown") {}
	Entity(const String& name) : m_Name(name) {}
	const String& GetName() const {
		return m_Name;
	};
};
int main() {
  // new keyword is used to allocate memory on heap
	int* b = new int; // new keyword will call the c function malloc which will allocate on heap  memory = data and return a ptr to that plaock of memory
	int* c = new int[50];
	Entity* e1 = new Entity;//new keyword Not allocating only memory but also calling the constructor
	Entity* e = new Entity[50];
	//usually calling new will  call underlined c function malloc
	//malloc(50); 
	Entity* alloc = (Entity*)malloc(sizeof(Entity));//will not call constructor only  allocate memory = memory of entity
	delete e;//calls a c function free
	Entity* e3 = new(c) Entity();//Placement New
}

Tags:

Cpp Example