繁体   English   中英

指针和复发 - 我正在努力节省记忆

[英]Pointers and recurency - I'm trying to save memory

我正在尝试编写为字符串创建squere的程序。 Squere必须大于string.length()。 如果有'C ++'字样,我需要2x2数组来填充它。 所以我写了代码

 #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);
    }
}

我敢打赌,使用具有recunrency的指针可以节省大量内存,但我无法编译它。 我正在努力理解编译器错误,但对我来说很难; /

这是编译器错误列表

> 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]

这里:

pole(pole, code.length());

您将第二个变量作为length()的结果传递,它的类型为std::string::size_type ,函数pole接受指向int的指针。 这两种类型是不兼容的。

第二个问题是你的if语句在pole内的一个分支不包含return语句,因此给你的程序Undefined Behavior。

您可能希望以这种方式更改功能pole

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!
    }
}

在这里,您可以看到您修改的程序编译和运行。

您正在尝试使用无符号整数 (来自std::string::length )作为指针:

pole(wall,code.length());

将您的极点声明更改为:

int pole(int a, int l);

int上保存内存只是废话。 指针有时甚至比简单整数更昂贵。

您应该学会用大型对象来节省内存。

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

首先,您不能使用size_t参数初始化int* l 你也可以在以后比较地址,而不是指向值。 这是你想要的吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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