I have to create push function with dynamic allocation using new instead of realloc/malloc. I already build program working fine but with malloc and calloc functions and because im starting learning c++ i dont know how to change that to use new instead of malloc. I also should double memory avaible for stack while program run out of avaible memory. Here is stack.cpp code:
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include "stack.h"
stack::stack()
{
this->top = 0;
this->data= (int *)malloc(0 * sizeof(int));
}
stack::~stack()
{
free(this->data);
}
void stack::clear()
{
this->top = 0;
}
void stack::push(int a)
{
i = i * 2;
assert(this->top < STACKSIZE);
int *ptr = (int *)realloc(data, (this->top + 1) * sizeof(int));
if (ptr == NULL)
{
return;
}
this->data = ptr;
this->data[this->top++] = a;
}
int stack::pop()
{
assert(this->top > 0);
return this->data[--this->top];
}
and there is header file:
#define STACKSIZE 20
class stack
{
public:
void push(int a);
int pop();
void clear();
stack();
~stack();
private:
int top;
int *data;
};