Search code examples
c++functionpointersreferencerecurrence

Pointers and recurency - I'm trying to save memory


I'm trying to write program that create squere for string. Squere has to be larger then string.length(). If there is word 'C++' I need 2x2 array to fill it inside. So I have written code

 #include <cmath>
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
int pole(int &a,const int* l);
int main(){
    string code;
    cin >> code;
    int wall=1;
    pole(wall,code.length());
    cout << wall;
    system("PAUSE");
    return 0;
}
int pole(int &a,const int* l){
    if (a*a > l) return a;
    else {
    a+=1;
    pole(a,l);
    }
}

I bet that using pointer with recunrency save a lot of memory but I can't compile it. I'm trying to understand compilers error but is 2 hard for me ;/

Here is compiler list of errors

> in main() 
11 25 Error] invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int (*)(int&, const int*)' 
 6 5> [Error] in passing argument 1 of 'int pole(int&, const int*)' 
 in pole() 17 12 
>[Error] ISO C++ forbids comparison between pointer and
> integer [-fpermissive]

Solution

  • Here:

    pole(pole, code.length());
    

    You are passing as the second variable the result of length(), which is of type std::string::size_type, which the function pole accepts a pointer to int. Those two types are incompatible.

    The second problem is that one branch of your if statement inside pole does not contain a return statement, thus giving your program Undefined Behavior.

    You may want to change your function pole this way:

    int pole(int &a, std::string::size_type l) {
    //               ^^^^^^^^^^^^^^^^^^^^^^
    //               Also, passing by reference is unnecessary here
    
        if (a*a > static_cast<int>(l)) return a;
    //            ^^^^^^^^^^^^^^^^
    //            Just to communicate that you are aware of the
    //            signed-to-unsigned comparison here
        else {
        a+=1;
        return pole(a,l);
    //  ^^^^^^
    //  Do not forget this, or your program will have Undefined Behavior!
        }
    }
    

    Here you can see your modified program compile and run.