0

I have been skimming around the website trying to find answer to my question, but I can't seem to find it. I was wondering why I am getting an strange number when trying to increase my pointer to int value.

At first I thought it might be because I didn't enclose my variable *sum with braces, but it does not help either.

I dont really see why I am unable to continuously increase sum pointer :@. I am assuming I am changing the address of sum instead of the value, but I am not sure why.

int userNumber;
int * sum = new int;
while (std::cin >> userNumber)
{
    if (userNumber == 0)
        break;
    else
        (*sum) += userNumber;
}
std::cout << "Loop ended with value: " << *sum << std::endl;

Any help would be lovely!

2
  • Why not print the value at the beginning of the loop? Commented Jan 21, 2018 at 20:42
  • You can jump straight into the question Commented Jan 21, 2018 at 21:04

1 Answer 1

3

When you allocate the int with new int, it is not initialized. Its value will be indeterminate and using it in any way without initialization will lead to undefined behavior.

You need to initialize it, which you can do with the allocation:

int * sum = new int(0);
Sign up to request clarification or add additional context in comments.

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.