简体   繁体   中英

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]

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.

You are trying to use an unsigned integer (coming from std::string::length ) as a pointer in:

pole(wall,code.length());

Change your pole declarations to:

int pole(int a, int l);

Saving memory on int is just nonsense there. Pointers are sometimes even more memory expensive than simple integers.

You should learn to save memory with huge objects instead.

int pole(int &a,const int* l){
    if (a*a > l) return a;
    else {
    a+=1;
    pole(a,l);
    }
}

first, you cannot initialize int* l with size_t argument. Also you do later comparison between address, not value pointed too. Is this what you wanted?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM