Home > front end >  Can't modify a string in C array
Can't modify a string in C array

Time:02-10

Trying to learn datastructures, I made this class for a stack. It works just fine with integers but it throws a mysterious error with strings. The class List is the API for my stack. Its meant to resize automatically when it reaches the limit. The whole code is just for the sake of learning but the error I get doesn't make any sense and it happens somewhere in some assembly code.

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


class List {
private:
    
    int N = 0;
    string* list = new string[1];
    void resize(int sz) {
        max = sz;
        string* oldlist = list;
        string* list = new string[max];
        for (int i = 0; i < N; i  ) {
            list[i] = oldlist[i];
        }

    }
    int max = 1;
public:
    void push(string str) {
        if (N == max) {
            resize(2 * N);
        }
        cout << max << endl;
        list[N] = str;
        N  ;
    }
    void pop() {
        cout << list[--N] << endl;
    }


};
int main()
{

    string in;
    List list;
    while (true) {
        cin >> in;
        if (in == "-") {
            list.pop();
        }
        else {
            list.push(in);
        }
    }
}

CodePudding user response:

string* list = new string[max]; in the resize method defines a new variable named list that "shadows", replaces, the member variable list. The member list goes unchanged and the local variable list goes out of scope at the end of the function, losing all of the work.

To fix: Change

string* list = new string[max];

to

list = new string[max];

so that the function will use the member variable.

Don't forget to delete[] oldlist; when you're done with it to free up the storage it points at.

  • Related