dimanche 21 janvier 2018

Set pointer to int value in loop

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!

Aucun commentaire:

Enregistrer un commentaire