1

I am reading a double from the standard input and saving it into a variable d. I want to be able to do this an unspecified amount of times. I use the following code to create a pointer to d.

double *pd = new double;
pd = &d;

I then push this pointer into a constructed stack (list) class. But whenever I push more than one double it changes all of them (the pointer is the same).

Ex. push 2 and get an array [2]. push 3 and get array [3, 3] instead of [3, 2].

2
  • 5
    Why don't you just push in the doubles themselves? Commented Dec 11, 2012 at 23:48
  • 1
    You're losing a pointer to dynamically referenced memory. bad idea. Commented Dec 11, 2012 at 23:50

2 Answers 2

7

Why are you using pointers at all?

std::vector<double> v;

double d;
while (std::cin >> d)
    v.push_back(d);

Or as chris points out:

std::copy(std::istream_iterator<double>(std::cin),
          std::istream_iterator<double>(),
          std::back_inserter(v));
Sign up to request clarification or add additional context in comments.

1 Comment

You can also initialize the vector with istream_iterators for an identical effect.
1
*pd = d

instead of

pd = &d;

What you do is:

  • you have double d variable on stack
  • you create double and save its pointer in pd variable
  • then you save address to d variable in pd
  • and then you save address from pd on list

This means you have list of addresses to variable d (every single object on list is pointer to d variable).

4 Comments

Or you could do double *pd = new double(d); Even better, whateverStack.push(d);.
The stack used pushes a pointer so I have to create a pointer to push, unfortunately. But yes, thank you for the help!
@AstraMeyers, What does it do with the pointer? Perhaps you could push &d instead.
@AstraMeyers use a different stack then.

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.