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