Thread: Somthing Wrong With My Array

  1. #1
    Registered User
    Join Date
    Mar 2006
    Posts
    22

    Angry Somthing Wrong With My Array

    I have the following code. the temp_array seems to have some garbage value at the end even though i try to randomly distubute certain numbers to it. I went through the loop several times but couldn't get whats wrong. I really really appreciate if sombody can spot the error. Thankx for loking into it
    have a good day

    Code:
    void rand_gen(int need_num, int **array, int dim){
    
    	int n, m, *temp_array;
    	int i=0, b, g, new1 ;
    	int q,w,h;
    
    	temp_array = (int *)malloc(need_num * sizeof(int));
    
    	for(h=0;h<need_num;h++){
    		temp_array[h]=0;}
    
    	srand(time(NULL));
    
    	for (i=0;i<need_num;i++)
    	{
            b=rand()%need_num+1;   // random number with in need_num
    
    
    		//temp storing the rand # in a array temp
    		new1 = 1;
    		for(g=0;g<i;g++)
    			if(temp_array[g]==b){new1 = 0;}
    
    
    			if (new1 == 1){
    				temp_array[i]=b;}
    			else
    				i--;
    	}
    
    	
    
    
    //WHEN dim =5, need_num=24 
    printf("\ntemp arra 24 is %d\n\n\n", temp_array[24]);<<//why this prints Garbage ???????????
    Last edited by ypramesh; 04-01-2006 at 09:22 PM.

  2. #2
    Registered User
    Join Date
    Jun 2004
    Posts
    277

  3. #3
    Registered User
    Join Date
    Mar 2006
    Posts
    22
    hmm.. I donno does it have to do somthing with all array elements are not assigned a value??? I am lost pls help

  4. #4
    vae victus! skorman00's Avatar
    Join Date
    Nov 2003
    Posts
    594
    If need_num is 24, your array holds 24 items. Valid indexes would be 0-23.

  5. #5
    Registered User
    Join Date
    Mar 2006
    Posts
    22
    thankx so much for that advice it save me lot of time. again thanx a lot

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 05-29-2009, 07:25 PM
  2. What is wrong with this 2d array?
    By FoxeySoulSLayer in forum C++ Programming
    Replies: 9
    Last Post: 04-10-2009, 04:14 PM
  3. 2d array question
    By gmanUK in forum C Programming
    Replies: 2
    Last Post: 04-21-2006, 12:20 PM
  4. Type and nontype parameters w/overloading
    By Mr_LJ in forum C++ Programming
    Replies: 3
    Last Post: 01-02-2004, 01:01 AM
  5. God
    By datainjector in forum A Brief History of Cprogramming.com
    Replies: 746
    Last Post: 12-22-2002, 12:01 PM