0
#include <iostream>
#include <utility>
#include <vector>
using namespace std;

int main() {
    vector<pair<int, int>*> *v;
    pair<int, int> *x = new pair<int, int>();
    cin >> x->first >> x->second;
    v->push_back(x);
    cout << v->size() << endl;
    return 0;
}

Why does this code get run-time error? I dont understand. All I do is appending a pair pointer to a vector of pair pointer.

2
  • 1
    I don't do much C++, but I don't think v is initialised, because it's a pointer the object isn't created implicitly. vector<pair<int, int>*> *v = new vector<pair<int, int>*>(); should work. This would explain why you're getting a segfault - you're trying to access a null pointer v. Commented Aug 15, 2018 at 5:29
  • ... shit, basic mistake. Im so dump. Yea me too, Im kind switching to js which is more free to create a new object without initiallizing. Commented Aug 15, 2018 at 5:43

1 Answer 1

1

First of all: Vector definition should be (this resolves the run-time error):

vector<pair<int, int>*> v;

Second, you don't release the memory of the new pair. This will solve that issue too:

vector<pair<int, int>> v;
pair<int, int> x{ 0,0 };

A vector of pairs, rather than a vector of pair-pointers. On the other hand: If it necessary to use a vector of pointers, smart pointers is a better choice.

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

1 Comment

Im so dump. Thank you.

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.