4
Follows the statement:
Make a program that reads keyboard numbers and store them on one dynamically allocated array. The user will type in a sequence of numbers, no quantity limit. The numbers will be typed one by one and, if he wishes to close the data entry, he will enter the ZERO number. The data must be stored in the memory of this way
- Start with a dynamically allocated size 10 vector;
- Apos, if the allocated vector is full, allocate a new vector of the previous vector size by adding space for another 10 values (size N+10, where N starts with 10);
- Copy the values already typed from the initial area to this larger area and free the initial area memory;
- Repeat this procedure to expand dynamically with another 10 values the allocated vector each time it is full. So the vector will be 'expanded' by 10 values.
At final, display the read vector. Do not use the REALLOC function.
I’m pretty new yet, so there’s probably a lot of things wrong with my code.
I tried to use a second vector, pass everything to it, allocate 10 more spaces in the main vector and then pass it all on to it again.
However, when I type I get to 19 and the program stops. In the first 10, it works perfectly, but then when I allocate another 10 (in case the vector would have 20 spaces) it doesn’t work.
Follow the code I made:
#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;
}
And why not use
realloc()
? Anything else you can’t use? I can see several problems in the code.– Maniero
because it is in the statement.. only that very says not to use
– ISABELA
What is this:
for (int i=0; i<c2; i++) vet[i] = vet[i];
? Ps: It is better to write the statement. It is not possible to understand very well by your code– thxmxx
ah, this part I had fixed but could not save (power outage). now I tidied up there. is vet[i] = vet1[i] to pass everything that is in vet1 to the vet
– ISABELA