-4

here is my code:

vector<int *> *ptr;
int *tab = new int(20);
ptr->push_back(tab);
cout << *(ptr->at(0)) << endl;

I want to print 20 on the screen, but I got a segmentation fault. when I use only

vector<int *> ptr;

it prints out fine. I get easily the result just by doing :

*ptr.at(0);

But I want to use a pointer not a simple variable. Can I have some enlightenment?

Thanks

djasy3
  • 25
  • 7
  • 3
    This is a Q&A site. What you need is a basic book/tutorial. This is not at all how C++ pointers work. – patatahooligan Jan 29 '18 at 16:39
  • 2
    are you trying to become a [three-star-programmer](http://wiki.c2.com/?ThreeStarProgrammer) ? if yes, you are on a good way, if no, you can remove most of your `*` – 463035818_is_not_an_ai Jan 29 '18 at 16:40
  • 1
    I don't understand why you want to use excessive layers of pointers. –  Jan 29 '18 at 16:42
  • 1
    there is no good reason to have a `std::vector` unless you have the `int`s already stored somewhere and want to point to them, which doesnt seem to be the case here and even then it is questionable (...or to become a 3-star-programmer ;) – 463035818_is_not_an_ai Jan 29 '18 at 16:43
  • 1
    did someone said 3-star-programmer, **((*ptr).data()) – MoonBun Jan 29 '18 at 16:49

1 Answers1

-1

Ignoring for the time being the reason for using pointers ...

vector<int *> *ptr;
int *tab = new int(20);
ptr->push_back(tab);

is a problem since you have not allocated memory for ptr.

Use:

// Allocate memory for ptr first.
vector<int *>* ptr = new vector<int*>;
int *tab = new int(20);
ptr->push_back(tab);
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • 2
    There are many things wrong with OP's code and this answer which neglects to point out that these pointers are necessary and leak memory is potentially doing more harm than good to OP. – patatahooligan Jan 29 '18 at 16:44
  • @r-sahu : Thanks, that makes sense now. it is clear. – djasy3 Jan 29 '18 at 16:52
  • @patatahooligan I think OP's thank-you comment verifies your point. –  Jan 29 '18 at 16:53