The statement follows:
Make a program that reads keyboard numbers and stores them in a vector dynamically allocated. The user will enter a sequence of numbers, with no quantity limit. The numbers will be typed one by one and, in case he wishes to close the data entry, he will enter the number ZERO. The data must be stored in the memory of this mode
- Start with a dynamically allocated size 10 vector;
- Then, if the allocated vector is full, allocate a new vector the size of the previous vector by adding space to another 10 values (size N + 10, where N starts with 10);
- Copy the already typed values from the starting area to this larger area and free the memory of the initial area;
- Repeat this procedure to dynamically expand with 10 more values to the allocated vector each time it is full. So the vector will be 'expanded' by 10 in 10 values.
At the end, display the read vector. Do not use the REALLOC function.
I'm pretty fresh yet, so there's probably a lot of wrong things in my code.
I tried to use a second vector, move everything to it, allocate 10 more spaces in the main vector and then move everything to it again.
But when I type, I get to 19 and the program stops. In the first 10, it works perfectly, but then when I go to allocate another 10 (in case the vector would have 20 spaces) it does not work.
Here is the code I did:
#include <stdio.h>
#include <stdlib.h>
int main(){
int *vet, c=1, c2=0, *vet1, aux;
vet =(int*) calloc(10, sizeof(int));
do {
scanf("%d", &aux);
if (c == 10){
vet1 = (int*) malloc (c2 * sizeof(int));
for (int i=0; i<c2+1; i++) vet1[i] = vet[i];
vet = (int*) malloc (c2 * sizeof(int));
for (int i=0; i<c2; i++) vet[i] = vet1[i];
c = 1;
}
c++;
c2++;
vet[c2] = aux;
} while (aux != 0);
printf("\n\n") ;
for (int i=0; i<c2; i++) printf("%d ", vet[i]);
system("pause");
return 0;
}