0

I am a Java programmer trying out c++, and I am not used to manual memory management.

I wrote a piece of code which attempts to generate a sierpiński triangle, and it was roughly ported from Java to C++. The Java code works but its C++ equivalent does not:

#include <vector>
#include <string>
using namespace std;

int main() {
    long unsigned int n;
    cin >> n;
    std::vector<string> arr(1);
    arr.at(0) = "\\";
    for(long unsigned int i = 0; i < n; i++){
        int size = arr.size();
        arr.resize(size*2);
        for(int ii = 0; ii < size; ii++){
            string t = "";
            t.append(arr.at(ii));
            for(long unsigned int i2 = 0; i2 < size-sizeof(t); i2++){
                t.append(" ");
            }
            t.append(arr.at(ii));
            arr.at(size+ii) = t;
        }
    }
    for(long unsigned int i = 0; i < arr.size(); i++){
        cout << arr.at(i) << endl;
    }
    return 0;
}

I know the issue has something to do with vectors, but it could also have something to do with memory management as the program would start to consume a lot of memory and never exit.

Rain
  • 37
  • 6
  • 2
    `sizeof(t)` doesn't do what you think. You probably want `t.length()`. – Nate Eldredge Nov 30 '20 at 00:24
  • 2
    *and it was roughly ported from Java to C++. The Java code works but its C++ equivalent does not:* -- Java is not C++, C++ is not Java. Attempting to convert Java code to C++ by doing line-by-line translations will result in either buggy code, inefficient code, or code that just looks weird to a C++ programmer. Do not use Java as a model in writing C++ code. – PaulMcKenzie Nov 30 '20 at 00:28

0 Answers0