By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,655 Members | 1,005 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,655 IT Pros & Developers. It's quick & easy.

realloc() help

P: 1
I can't figure out what might be wrong in that piece of code. The window keeps shutting down after having entered a few integers and -1 (in order to terminate the function). Am I using realloc() improperly or what? Thanks in advance for any help?

Expand|Select|Wrap|Line Numbers
  1.  
  2. #include <iostream>
  3. #include <stdio.h>
  4. using namespace std;
  5. #define CHUNKSZ 5
  6.  
  7. void printScores( int ** );
  8. void getScores( int** );
  9.  
  10. int main()
  11. {    
  12.     int *score = NULL;
  13.  
  14.     getScores( &score );
  15.  
  16.     printScores( &score );    
  17.  
  18.     system("pause");
  19. }
  20.  
  21. void getScores( int ** test )
  22. {
  23.      int score;
  24.      int i = 0;
  25.      int number;
  26.      int* hold = NULL;
  27.  
  28.      number = CHUNKSZ;
  29.      *test = ( int* )malloc( sizeof( int ) * CHUNKSZ );
  30.  
  31.      while(9)
  32.       {
  33.         for( ; i < number; i++ )
  34.            {  cout << endl <<"Enter a score ( -1 to stop )"<<i<<" : ";
  35.               cin >> score;
  36.               if ( score == -1 )
  37.                 {  (*test)[i] = -1;
  38.                     return;
  39.                  }
  40.              (*test)[i] = score;
  41.            }  
  42.  
  43.         if( ( hold = ( int* )realloc( *test , sizeof( int ) * CHUNKSZ )) == NULL)
  44.           cout << endl << "Allocation error." ;
  45.         else { *test = hold; 
  46.                number += CHUNKSZ;
  47.                hold=NULL; }
  48.      }
  49. }
  50.  
  51. void printScores( int **test ) 
  52. {
  53.      int i = 0;
  54.      for( ; *( *test + i ) != -1; i++ )
  55.         cout << endl <<"Score : " << *( *test + i );
  56.      cout << endl; 
  57. }
  58.  
Feb 19 '07 #1
Share this Question
Share on Google+
1 Reply


Ganon11
Expert 2.5K+
P: 3,652
Please don't double post your question - your second thread has been deleted.
Feb 19 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.