Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing new value to a pointer via a recursive function in c++

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){

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
       }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading