vendredi 15 novembre 2019

Class member value overwritten by previous member

If I create a two class members of char* type and is array. And if I resize first member of the class it overwrite the second member with same values. Why it happens? Is it some memory management issues?

#include <iostream>

using namespace std;

class myclass
{
    private:
        const char *arr1[0];
        const char *arr2[4] {
            "one",
            "two",
            "three",
            "four"
        };
    public:
        void run() {
            int f = 0;

            *this->arr1 = new char[4];

            for(f = 0; f < 4; f++) {
                this->arr1[f] = "foo";
            }

            for(f = 0; f < 4; f++) {
                cout << this->arr2[f] << endl;
            }
        }
};

int main()
{
    myclass *my = new myclass();
    my->run();

    return 0;
}

Output

foo
foo
foo
foo

Aucun commentaire:

Enregistrer un commentaire