I have a class defined in a header file, Array.h.
Class Code:
class Array
{
private:
int length;
void **data;
public:
Array();
void push(void *);
};
I also have the Array.cpp file.
Code:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "Array.h"
Array::Array()
{
length = 0;
data = NULL;
}
void Array::push(void *item)
{
void **temp = new void *[length + 1];
for (int i = 0; i < length; i++)
temp[i] = data[i];
temp[length] = item;
data = temp;
length++;
}
And finally, main.cpp.
Code:
#include <stdio.h>
#include "Libs/Array.h"
void loadArray();
int main()
{
loadArray();
return 0;
}
void loadArray()
{
Array ints = Array();
while (true)
{
printf("Array (Size: %d): ", ints.size());
for (int i = 0; i < ints.size(); i++)
printf("%d ", *((int *)ints.get(i)));
printf("\n");
printf("1] Push\n2] Pop\n3] Set\n4] Get\n5] Clear\n6] Shift\n7] Unshift\n8] Size\n\n9] Exit\n");
printf("Choice: ");
int choice;
scanf("%d", &choice);
printf("\n\n");
bool shouldExit = false;
switch (choice)
{
case 1:
{
int x;
printf("Enter a number: ");
scanf("%d", &x);
ints.push(&x);
printf("\n\n");
break;
}
(...)
}
if (shouldExit)
break;
}
}
When I push the first value, it successfully pushes into the array. But when I push any more values, the initial values are simply replaced by the new push value.
Output (Pastebin):
Why is this happening? I am really confused about this. Any help is appreciated.
