Wrote a program to read as many positive integers as possible using realloc to store, and to output them after 0 is entered.
Code:
#include<stdio.h>
#include<stdlib.h>
int main(void){
int *p=(int *)malloc(sizeof(int)),data_counter=0,i;
puts("This programme inputs positive integers...\n");
for(;;){
printf("Input an integer or 0 to quit: ");
scanf("%d",&(p[data_counter]));
if(!p[data_counter]) break;
data_counter++;
realloc(p,(1+data_counter)*sizeof(int));
}
printf("\nYou have input %d data integers. They are: ",data_counter);
for(i=0;i<data_counter;i++){
printf("\n%d",p[i]);
}
free(p);
while(getchar()!='\n'); getchar();
return 0;
}
When compiled and ran, like inputting 2,3,4,5,6, it would display the five numbers after 0 is typed. but the prob is the 1st integer is some garbage value, whereas the rest are totally fine. In fact this garbage value appeared after the realloc() is applied. Any remedy for this?