Home > Blockchain >  Passing new value to a pointer via a recursive function in c
Passing new value to a pointer via a recursive function in c

Time:01-02

How I can change the value of p to 1 passing it as an argument to a recursive function. This is my code:

class Solution
{
   void g(int n,int k,int *p){
       if(k==0) return;
       if(k%n==0) g(n,k-1,1);
       cout<<p<< endl;
       g(n,k-1,p 1);
   }
   public:
       int josephus(int n, int k)
           { int p=1;
           g(n,k,&p);
           return p;
       }
};

I get this errors:

prog.cpp: In member function void Solution::g(int, int, int*):
prog.cpp:14:21: error: invalid conversion from int to int* [-fpermissive]
 if(k%n==0) g(n,k-1,1);
                     ^
prog.cpp:12:9: note:   initializing argument 3 of void Solution::g(int, int, int*)
    void g(int n,int k,int *p){

CodePudding user response:

The error says you cannot pass an int as a parameter to a function when it expects an int *.

There is also a logical bug in your code:

       g(n,k-1,p 1);

This recursive call increments the pointer value, which makes it point past the passed in object, since the function was called like this:

           { int p=1;
           g(n,k,&p);

Since your function takes an int *, you need to dereference the pointer to manipulate the referenced object. So, you probably intend to increment *p and then make the recursive call:

         *p;
       g(n,k-1,p);

To address the compilation error, you probably intended to assign 1 to the int object and make the recursive call.

       if(k%n==0) {
           *p = 1;
           g(n,k-1,p);
       }
  • Related