Results 1 to 3 of 3

Thread: CPP Problem :

  1. #1
    Banksy's Avatar



    Join Date
    Jun 30, 2009
    Last Online
    Jan 14, 2010
    Posts
    100
    Threads
    17



    CPP Problem :


    hey, i have to write a recursive function that computes the factorial of a number given the following prototype:

    Code:
    void factorial (long argument, long *result)

    here's what i have written, it compiles, but whenever i run it i get a segmentation fault. i'm pretty sure i'm just not using the pointer properly, any help would be greatly appreciated.

    Code:
    #include <stdio> 
    
    void factorial(long argument, long *result); 
    
    int main(){
    	long a;
    	long *result;
    
    	*result = 1;
        
        	printf("Enter a number: ");
        	scanf("%l", &a);
    
    	factorial(a, result);
    
        	return 0;
    }
    
    void factorial(long argument, long *result){
    	if (argument == 1)
    		printf("The factorial of %l is: %l", argument,*result);
    	else{
    		*result = *result * argument;
    		factorial(argument-1, result);	
    	}
    }

    i'm pretty new to C so if there are any other obvious flaws feel free to point them out.

  2. #2
    Drunken F00l's Avatar



    Join Date
    Dec 11, 2004
    Last Online
    Jun 11, 2019
    Posts
    5,874
    Threads
    182
    Reputation
    SourceOP Thread


        
    Steam: 76561197968459473 
    Steam join date: Aug 23, 2004
    Steam Level: 56
    Profile Status: Public


    Re: CPP Problem :


    Quote Originally Posted by Banksy
    Code:
    	long *result;
    
    	*result = 1;
    Stopped reading right there. (Read: There's your obvious flaw.)

  3. #3
    OmegaZero_Alpha's Avatar



    Join Date
    Jan 02, 2005
    Last Online
    Jul 16, 2019
    Posts
    4,880
    Threads
    253
    Reputation
    SourceOP Thread


        
    Steam: 76561197979925166 
    Steam join date: Dec 24, 2005
    Steam Level: 44
    Profile Status: Public



    long result is loooooooooooooooooooooooooooooooooooooooooooong

Tags for this Thread