use of realloc

This is a discussion on use of realloc within the C Programming forums, part of the General Programming Boards category; I can't understand how realloc works.I make this code #include <stdio.h> #include <stdlib.h> Code: int main(void) { int *p=(int *)malloc(5*sizeof(int)); ...

  1. #1
    Registered User
    Join Date
    Aug 2007
    Posts
    63

    use of realloc

    I can't understand how realloc works.I make this code
    #include <stdio.h>
    #include <stdlib.h>

    Code:
    int main(void)
    {
      int *p=(int *)malloc(5*sizeof(int));
      int i;
    
     for(i=0; i<5; i++)
       scanf("%d",&p[i]);
     for(i=0; i<2; i++)
       printf("%d", p[i]);
     printf("new elements");
    
     p=(int *)realloc(p,10*sizeof(int));
    
    
     for(i=5; i<10; i++);
     scanf("%d", &p[i]);
    
    
    
     return 0;
    }
    first it asks memory for 5 int.After i put 5 numbers and i print the first 2 numbers.Then use realloc in order to put 5 more numbers but when i give the first number and then enter the programm finishes?Why?I think that should ask me for 5 numbers and not for one.

  2. #2
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,807
    Code:
    for(i=5; i<10; i++);
    should be
    Code:
     for(i=5; i<10; i++)

  3. #3
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,682
    And always check the return value of the malloc and realloc. And dont type cast the malloc and realloc function. See FAQ

    ssharish

  4. #4
    Registered User
    Join Date
    Aug 2007
    Posts
    63
    thank you very much, i know that i must check the return value

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. did i understood right this explantion of realloc..
    By transgalactic2 in forum C Programming
    Replies: 3
    Last Post: 10-24-2008, 07:26 AM
  2. writing a pack-style function, any advices?
    By isaac_s in forum C Programming
    Replies: 10
    Last Post: 07-08-2006, 08:09 PM
  3. using realloc
    By bobthebullet990 in forum C Programming
    Replies: 14
    Last Post: 12-06-2005, 04:00 PM
  4. segfault on realloc
    By ziel in forum C Programming
    Replies: 5
    Last Post: 03-16-2003, 03:40 PM
  5. Realloc inappropriate for aligned blocks - Alternatives?
    By zeckensack in forum C Programming
    Replies: 2
    Last Post: 03-20-2002, 01:10 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21