0

I have been trying to calculate factorials of numbers from 0 to 10 using for loop and pass by reference. when I executes the lines outside of the loop(those which are now commented out) it works fine but when I use the loop parameter's pointer as the input, it out puts the following regardless of the range of i: 1 1 2 6 5040 & Here is my code:

    #include<stdio.h>
int fact(int*);
int main(void)
{
   // int n;
   // scanf("%d",&n);
   // printf("%d\n",fact(&n));
   for (int i = 0; i < 15; i++)
   {
      printf("%d\n",fact(&i));
   }
   return 0;
}
int fact(int *a)
{
   if (*a==0 || *a==1)
   {
      return (1) ;
   }
   
   for (int i = *a -1; i > 0; i--)
   {
      *a*=i;
   }
   return *a;
}

& when I try to debug, the panel just prints that the build was finished successfully and when I press Enter it closes. I have tried all YouTube guides with no success.

rioV8
  • 24,506
  • 3
  • 32
  • 49
woods
  • 1
  • 1
  • 4
    You are changing the value of `i` thru the call of `fact` since it is passed in as a pointer and changed inside the function. Which messes up the loop counter. Why do you want to pass in a pointer anyway? – kaylum Aug 16 '21 at 05:36
  • I did merely for sake of practice. – woods Aug 16 '21 at 05:38
  • yet I dont follow how it changes the value of i. could you elaborate? – woods Aug 16 '21 at 05:38
  • `*a` is essentially the caller's `i` variable. So if you set it you are setting `i`. That's what dereferencing a pointer does. There's really no reason to pass in a pointer - practice is ok but it would be better to practice with cases that actually need a pointer. – kaylum Aug 16 '21 at 05:39
  • In the line `*a*=i;`, `a` points to the variable `i` of the function `main`, so you are changing it with that line. Therefore, this `for` loop won't work: `for (int i = 0; i < 15; i++)`. If you change the loop counter inside the loop, you can't expect the loop to work properly. – Andreas Wenzel Aug 16 '21 at 05:42
  • If you have trouble getting your debugger to work in Visual Studio Code, then I suggest that you open a new question that focuses on that problem only. In that question, you should explain exactly what you tried and what is not working. – Andreas Wenzel Aug 16 '21 at 05:47
  • I have copied the content of vscode configuration file from the internet and changed their address to match to those in my pc with no success. I tried to use codeblocks debugger and that just gives me irrelevant data(I can't traces values for instance) – woods Aug 16 '21 at 05:52
  • @woods For the sake of practice, a few links that provide basic discussions of pointers may help. [Difference between char *pp and (char*) p?](https://stackoverflow.com/a/60519053/3422102) and [Pointer to pointer of structs indexing out of bounds(?)...](https://stackoverflow.com/a/60639540/3422102) (ignore the titles, the answers discuss pointer basics) – David C. Rankin Aug 16 '21 at 06:42

0 Answers0