I want to use a pointer to array to store all the intermediate results of factorial calculation. The code below get crush when running. Why and how can I modify the code so that it can run correctly?
int factorial(int x, int *p){
if (x>1){
*p = x*factorial(x-1, p+1);
return *p;
}
else{
*p = 1;
return 1;
}
}
Call it with
int *p = new int[10];
Your original code
int *p = new int(10);
means allocating space for one single int and initialize it as 10, not a 10-element array.