Algorithm
At the beginning the array is of length = 0. Then, in each iteration, when trying to enter an element, the array becomes of length + 1; then, said element occupies the position length-1.
Goal
That an element is entered into the array and it changes its length as each iteration occurs.
Problem
The program closes (APPCRASH) by entering a few values.
Implementation
#include <cstdlib>
#include <malloc.h>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int *arreglo, i;
bool seguir=true;
size_t longitud=0;
arreglo=(int*)malloc(longitud*sizeof(int));
while (seguir!=false) {
arreglo=(int*)realloc(arreglo,(1)*sizeof(int));
longitud++;
arreglo[longitud-1]=5;
cout<<"seguir: ";
cin>>seguir;
}
for (i=0;i<longitud;i++) cout<<"arreglo["<<i<<"]="<<arreglo[i]<<endl;
free(arreglo);
system("pause");
return 0;
}
I do not realize what conceptual mistakes I'm making. I have tried several possibilities and the problems persist.
Try to simplify as much as possible the program (to such an extent that the only element that is entered is 5). The original idea was to implement a class to represent the set of integers by a dynamic array, and in that class to define operations on those sets. But the fact is that it is difficult for me to build the sets, and that does not let me move forward in the rest of the year.
I hope you can help me. It's the first time I ask for help with a code. Thank you very much.