2
 class Sesion
{
private:
         int wymiar = 2;
         int **tablica = new int *[wymiar];
         int licznik = 0;

    void save(int x, int y)
    {
            for (int i = 0; i < wymiar; i++)
                    tablica[i] = new int[wymiar];

            tablica[0][licznik] = x;
            tablica[1][licznik] = y;

            licznik++;
    }

    void open()
    {
            for (int i = 0; i < licznik; i++)
            {
                cout << tablica[0][i] << endl;
            }
    }
}

I dont know how to read value in open() because im getting weird numbers there.

In save() everything works perfect. Im must to save x and y in unlimited array and then read these values from it.

I know i can use Vector but i need to do it using Dynamic Array

1
  • 2
    Can you post the code you are using that produces the strange behavior? Commented May 19, 2014 at 18:57

2 Answers 2

3

You are complicating you life unnecessarily. Managing memory allocation/deallocation by yourself, in a safe manner, is going to be a PITA. Not to mention that your code is also affected by memory leak.

I've also noticed that you are always saving pair of ints. You should be using std::pair or a custom struct/class, in conjunction with an std::vector instead.

Here's an example:

class Sesion {
private:
    std::vector<std::pair<int, int>> tablica;
public:
    void save(int x, int y) {
        tablica.emplace_back(x, y);
    }

    void open() {
        for (auto p : tablica)
            std::cout << std::get<0>(p) << ',' << std::get<1>(p) << '\n';
    }
};

Live demo

Sign up to request clarification or add additional context in comments.

Comments

0

consider using std::vector, e.g.

class Sesion
{
private:
    struct Point { int x, y; };

    std::vector<Point> points_;

public:
    void save(int x, int y)
    {
        points_.push_back( Point{x, y} );
    }

    void open()
    {
        for ( Point const& point : points_ )
        {
            cout << point.x << " " << point.y << endl;
        }
    }
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.