Thread: Problem with Pointers and an Array

  1. #1
    Registered User
    Join Date
    Aug 2005
    Posts
    204

    Problem with Pointers and an Array

    I have some code that just does seem to work right. The code looks like this
    Code:
    #include <stdio.h>
    #include <math.h>
    
    int main() {
    	double a=1, b=1, *r;
    	int i=2, n=10;
    	r = malloc(n);
    	r[0] = 1; 
    	
    	while(i<n){
    		if( i%4 == 0){
    			a +=  1;
    			b += 2;
    		}
    		else if( i%2 == 0){
    			a += 3;
    			b += 4;
    		}
    			
    		r[i-1] = a;			
    		r[i] = b;		
    
    		i += 2;
    		
    	}
    	
        for(i = 0; i<n; i++){
    	 printf("r[%d] = %f \n",i, r[i]);   
        }  
    	    
    return 0;       
    }
    It should output something that looks like this
    Code:
    1
    2
    3
    5
    7
    6
    9
    8
    11
    Instead it outputs
    Code:
    1
    0
    0
    0
    0
    0
    0
    0
    Which is clearly not what I want.

    Does any one know how I can make this code work? What is wrong with it? I suspect it has something to do with my pointers, but I'm not positive.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > r = malloc(n);
    This allocates 10 bytes, not 10 doubles.

    r = malloc ( n * sizeof *r );

    Also, you didn't include stdlib.h. Did this compile without warnings?
    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