Im trying to create this and add push back functionality. How can i do it? I came up with this code but im very confused for 2 days because it gives this output - | -842150451 | -842150451 | -842150451 | -842150451 | -842150451 | -842150451 | -842150451 | -842150451 I will be thankful if someone can tell me how this function push_back should look or at least point me in the right direction. Also i would be thankful if you tell me where this code is doing wrong?
struct IntArray{
private:
int k;
int* first_cell;
int size; // currently occupied elements
int capacity = 8; // size of the allocated memory
public:
void create() {
first_cell = (int*)malloc(capacity * sizeof(int));
}
void random_numbers_fill(int limit) {
srand(time(NULL));
for (k = 0; k < capacity; k++) {
first_cell[k] = rand() % limit;
}
}
void push_back(int number) {
if (size == capacity) {
int* new_arr;
capacity *= 2;
new_arr = (int*)malloc(capacity * sizeof(int));
for (k = 0; k < capacity; k++) {
new_arr[k] = first_cell[k];
}
free(first_cell);
first_cell = new_arr;
first_cell[size] = number;
size++;
}
}
void print() {
for (k = 0; k < capacity; k++) {
printf("| %d ", first_cell[k]);
}