c++ - 指针和递归性——我正在努力节省内存

标签 c++ function pointers reference recurrence

我正在尝试编写为字符串创建正方形的程序。 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);
    }
}

我敢打赌,使用具有重复性的指针可以节省大量内存,但我无法编译它。我试图理解编译器错误,但对我来说很难 2 ;/

这是编译器的错误列表

> 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 的指针。这两种类型是不兼容的。

第二个问题是 pole 中的 if 语句的一个分支不包含 return 语句,从而使您的程序出现未定义行为.

您可能希望以这种方式更改函数 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!
    }
}

Here你可以看到修改后的程序编译运行。

关于c++ - 指针和递归性——我正在努力节省内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15453592/

相关文章:

c++ - 在另一个 VS 项目中引用函数模板的显式实例化时出现 LNK2019 错误

c++ - 是否为这个重载运算符调用了转换构造函数? (C++)

function - 单击特定条件 Odoo 13 显示导出操作的验证

c++ - 遍历指向类的指针 vector

c++ - 尝试将对象插入空指针数组时出现段错误

c++ - 从没有数组的文件中读取不同类型的数据

sql - 更新表中的每一行

javascript - 合并 2 个 Javascript 函数

c - 简单变量 i 和 *(&i) 之间的区别;

Java:可调整大小的数组列表不会保持平行