Dynamic allocation problem

2

I need to make a code where the user populates a vector as many times as he wants, but the code stops rolling. If I only register 3 values, like (1) (2) (3) it works normally, but at some moments (there is no default) the program stops running. I could not find my fault.

Follow the code:

#include<stdio.h>

main(){
int *vetor, i, d, contador=0; 
char c;
vetor=NULL;
do{
    if(contador==0)
        vetor=malloc(1*sizeof(int));
    else
        realloc(vetor,1*sizeof(int));
printf("Digite um valor para salvar no vetor: ");
scanf("%d", &d);
*(vetor+contador)=d;
contador++;
printf("Deseja cadastrar mais um numero? ");
scanf(" %c", &c);
system("pause");
} while(c == 's' || c == 'S');
system("cls");
for(i=0; i<contador; i++)
    printf(" (%d) ", vetor[i]);
}
    
asked by anonymous 03.06.2016 / 19:42

1 answer

2

The main problem is that the reallocation is always using the same size, it is not increasing and it is not assigning to a variable, this reallocation is lost, this generates the error. You have better ways to solve this, but for an exercise, that's fine. Change:

vetor = realloc(vetor, sizeof(int) * contador + 1);

See working on ideone (rephrased for a way that I like more and much more organized. In real code I would do a little bit differently ). Also in CodingGround .

    
03.06.2016 / 20:24