在C ++中通过引用传递的值调用函数?

时间:2017-10-01 19:11:25

标签: c++

我无法理解为什么* p和* p1的值在cout它们在下面的代码行中的值之后发生了变化。谢谢你的帮助。

void g(int *&x) {
    int a = 3;
    x = &a;
}
void h(const int *&x) {
    int b = 2;
    x = &b;
}

int main() {
    int *p = new int;
    *p = 5;

    g(p);
    cout << p << " " << *p << endl; // 0095FD48 3 *why the value change in the next line? *
    cout << p << " " << *p << endl; // 0095FD48 1829755776 
    const int*p1 = p;
    h(p1);
    cout << p << " " << *p << endl; // 0095FD48 2 *in here it happen, too*
    cout << p << " " << *p << endl; // 0095FD48 1829755776 
}

1 个答案:

答案 0 :(得分:3)

unsorted = ['B', 'D', 'A', 'G', 'F', 'E', 'H', 'C'] n = 4 num = float(len(unsorted))/n l = [ unsorted [i:i + int(num)] for i in range(0, (n-1)*int(num), int(num))] l.append(unsorted[(n-1)*int(num):]) print(l) complete = unsorted.split() print(complete) #include<iostream> #include<cmath> #include<cstdlib> using namespace std; float f(float x)//definition of the integrand { return sqrt(1-x*x); } float rand1()//random number generator between 0 and 1 { float s=rand(); return s/(RAND_MAX+1.0); } float calcint(float xi,float xf,float yi,float yf,float N)//integrator { float n=0; for(int i=0;i<N;i++) { float x=(xf-xi)*rand1();float y=(yf-yi)*rand1(); if (y<f(x)) { n=n+1; } } return n/N*(xf-xi)*(yf-yi); } int main() { float N=100000000; for (int i=1; i<N; i=i+N/10)//lists integration value for different sampling { cout<<i<<"\t"<<4*calcint(0,1,0,1,i)<<endl; } return 0; } 将本地变量的地址分配给参数,从而将地址公开给调用者。当这些函数返回时,局部变量被释放,即它在堆栈上的位置可以被重用。

因此,这是未定义的行为。在您的示例中,这是&#34;在免费使用后的情况&#34;。

g()及其h()的调用使用堆栈的某些部分并覆盖&#34;以前的本地变量&#34;。

您的示例代码有几种修复方法,具体取决于您希望实现的目标:

  1. 如果您希望函数修改main函数的cout值,则不要在operator<<中引入新的整数变量,而是访问现有的变量: *p

  2. 与(1)基本相同,但是你没有引用而不是指针。 g()

  3. 分配一个新变量。 void g(int *&x) { *x=3; } 因为您将指针作为引用传递,所以前指针值将被覆盖,这可能会导致内存泄漏。
  4. 与(3)相同,但使用返回值,从而降低内存泄漏的风险: void g(int &x) { x=3; // x is no local variable but references the callers argument }

  5. 为避免内存泄漏,您可以使用&#34;自动指针&#34;,请参阅http://www.cplusplus.com/reference/memory/unique_ptr/

相关问题