Thread: Input numbers using realloc

  1. #1
    Registered User
    Join Date
    Jan 2005
    Posts
    4

    Input numbers using realloc

    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?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,663
    Search the board for how people (like me) use realloc.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. entering numbers to array in a row whithout length input
    By transgalactic2 in forum C Programming
    Replies: 55
    Last Post: 01-02-2009, 04:02 AM
  2. Need some help with C program writing
    By The_PC_Gamer in forum C Programming
    Replies: 9
    Last Post: 02-12-2008, 09:12 PM
  3. For loop problems, input please.
    By xIcyx in forum C Programming
    Replies: 2
    Last Post: 04-22-2007, 03:54 AM
  4. I would love some input on my BST tree.
    By StevenGarcia in forum C++ Programming
    Replies: 4
    Last Post: 01-15-2007, 01:22 AM
  5. Can we input negative numbers in the output windiw
    By hitesh1511 in forum C Programming
    Replies: 1
    Last Post: 08-22-2006, 12:07 AM