指针和重复周期 - 我正在尝试节省内存

Pointers and recurency - I'm trying to save memory

本文关键字:节省 内存 周期 指针      更新时间:2023-10-16

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

我敢打赌,使用带有记录的指针可以节省大量内存,但我无法编译它。我试图理解编译器错误,但对我来说很难 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!
    }
}

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

您正在尝试使用无符号整数(来自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。你也做稍后的地址比较,而不是值指向。这是你想要的吗?