-2
void assignVal(int *loopCount)
{
    //lots of stuff with print statements to know where func stop executing

    cout << "before assign resultCount" << endl;

    *loopCount = 3; //I want the loopSize int in the main function to be equal to 3;

    cout << "after assign resultCount" << endl;

    return;
}

int main() 
{
    int loopSize;

    assignVal(&loopSize);
    //Doesn't get here or below
    for(int i = 0; i < loopSize; i++)
    {
        cout << i << endl;
    }
}

I am trying to pass in the variable loopSize to be assigned inside the function assignVal(int*). I have no control over the main function, this is for hackerank (this is obviously not the code from the problem, i am just showing a heavily modified version of the small part that isn't working for me. I also have no control of the assignVal(int*) function signature. I need to receive this int*, change it within the function, and then just return. I don't know why this isn't working, this is how I would do it anywhere else. The cout "after assign resultCount" never gets printed, and the program stops executing there. I can confirm it IS compiling.

Edit: It should be noted that if I assign loopCount like this

int* arr = {3};
loopCount = arr;

The function continues to execute just fine, but the value outside the function is incorrect for some reason.

1 Answers1

0

It is not passed by reference, it is a pointer. Raw pointers need careful management to avoid problems. You can pass by reference like this:

void assignVal(int & loopCount)

You can read more here: What's the difference between passing by reference vs. passing by value?

Cosmin
  • 21,216
  • 5
  • 45
  • 60