0

What is wrong with the following code

vector < double >* a;
a->push_back(25);
a->push_back(30);
a->push_back(15);
a->push_back(40);
cout << a->at(2) << endl;

It should print 15, but it prints nothing

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
mpelia
  • 43
  • 3

3 Answers3

1

a is a pointer but is not properly initialized... it must be like:

int main()
{
    std::vector<double>* a = new std::vector<double>;
    a->push_back(25);
    a->push_back(30);
    a->push_back(15);
    a->push_back(40);
    std::cout << a->at(2) << std::endl;
    delete a;
    return 0;
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
1

What is wrong ...?

You are using a pointer where an automatic duration value is more appropriate.

std::vector < double > a;
a.push_back(25);
a.push_back(30);
a.push_back(15);
a.push_back(40);
std::cout << a.at(2) << std::endl;
Caleth
  • 52,200
  • 2
  • 44
  • 75
-1

Your pointer wasn't initialized. Additionally, based on the answer by ΦXocę 웃 Пepeúpa ツ, make sure when you are working with pointers to use new/delete correctly. For every new keyword, there should be a delete. It is also good practice to avoid dangling pointers (pointers that do not reference anything) by setting them to NULL (as of C++11, it's recommended to use nullptr: NULL vs nullptr (Why was it replaced?) and What exactly is nullptr? questions offer some good explanations) when you are done.

However, in this case, I agree with Acorn. You shouldn't have to point to a vectorobject because of how it allocates memory. It should be sufficient to just use a vector for your solution.

jameyb
  • 37
  • 7
  • `It is also good practice to avoid dangling pointers (pointers that do not reference anything) by setting them to NULL` - nothing good about this anti-pattern. – SergeyA Nov 28 '18 at 20:35
  • Please clarify? I specifically stated that `nullptr` is better than using `NULL`. What is not good here? – jameyb Nov 28 '18 at 20:39
  • It is not about nullptr vs null. It is about that setting pointer to nullptr after deleting is is a false safety and antipattern. – SergeyA Nov 28 '18 at 20:42
  • Well, it depends doesn't it? Perhaps if you want to discuss this later it'd be more appropriate to talk in the chat or something. I am confused as to exactly how you can claim it is false. Reading through the question and answers below, it seems that it really does depend: https://stackoverflow.com/questions/1931126/is-it-good-practice-to-null-a-pointer-after-deleting-it – jameyb Nov 28 '18 at 20:48
  • 1
    See https://stackoverflow.com/questions/704466/why-doesnt-delete-set-the-pointer-to-null (some answers after the top one). The main problem with that is false sense of safety. Even on your own link, it is mentioned that it is a bandaid over fundamental problem. WHY your application deletes the pointer twice? It could be argued that it is better to let it crash rather than mask the problem, until it pops somewhere else. – SergeyA Nov 28 '18 at 20:53