将值赋给通过引用传递的int会停止程序执行

问题描述 投票:-2回答:1
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;
    }
}

我试图传递变量loopSize在函数assignVal(int*)内分配。我无法控制主要功能,这是hackerank(这显然不是问题的代码,我只是显示了一个对我不起作用的小部件的大量修改版本。我也无法控制assignVal(int*)函数签名。我需要接收这个int *,在函数内更改它,然后返回。我不知道为什么这不起作用,这就是我在其他任何地方都会这样做.cout“之后分配resultCount“永远不会打印,程序停止在那里执行。我可以确认它正在编译。

编辑:应该注意的是,如果我像这样分配loopCount

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

该函数继续执行得很好,但由于某种原因,函数外部的值不正确。

c++ reference pass-by-reference
1个回答
0
投票

它不是通过引用传递的,它是一个指针。原始指针需要仔细管理以避免问题。您可以像这样通过引用传递:

void assignVal(int & loopCount)

你可以在这里阅读更多:What's the difference between passing by reference vs. passing by value?

© www.soinside.com 2019 - 2024. All rights reserved.