【问题标题】:why does pointer get its previous value returning from a function为什么指针从函数返回其先前的值
【发布时间】:2011-08-18 02:11:52
【问题描述】:

各位,ptr 是如何得到它之前的值的呢?代码很简单,我只是想知道为什么它不存储在函数中分配的地址值。

#include<stdio.h>
#include<stdlib.h>
void test(int*);
int main( )
{
    int temp;
    int*ptr;   
    temp=3;
    ptr = &temp;
    test(ptr);


    printf("\nvalue of the pointed memory after exiting from the function:%d\n",*ptr);
    printf("\nvalue of the pointer after exiting from the function:%d\n",ptr);


system("pause ");
return 0;
} 


void test(int *tes){

    int temp2;        
    temp2=710;
    tes =&temp2;

    printf("\nvalue of the pointed memory inside the function%d\n",*tes);
    printf("\nvalue of the pointer inside the function%d\n",tes);


}

输出是:

函数内指向内存的值:710

函数内指针的值:3405940

函数退出后指向内存的值:3

退出函数后指针的值:3406180

【问题讨论】:

    标签: c++ pointers


    【解决方案1】:

    你通过值传递了指针。

    test 中的指针是main 中指针的副本。对副本所做的任何更改都不会影响原件。

    这可能会造成混淆,因为通过使用 int*,您将句柄(“引用”,尽管实际上引用是 C++ 中存在的单独事物)传递给 int,从而避免了那int。然而,指针本身就是一个对象,你通过值传递 that

    (您还试图将指针指向函数 test 的本地 int。使用它将无效。)

    【讨论】:

    • +1 为答案。但是不明白为什么指针指向函数的局部变量会无效。在 sn-p OP 中不是返回指针。
    • @Mahesh:不会,但如果他正确处理了指针,那么他就会遇到这个辅助问题。 :) “它”是指针的新值。那句话并不完全清楚;对不起。
    【解决方案2】:

    指针是按值传递给函数的,换句话说,它是一个副本。在函数中更改副本,但这不会改变 main 中的值。如果你想改变它,你需要使用一个指向指针的指针。

    【讨论】:

    • 您正在对int 值使用引用调用(即通过指针),但与指针本身无关。
    • @user675844:是的,对于int(通过“指针”;“通过引用”实际上是不同的,但我知道你的意思)。但不适用于指针本身。 :)
    【解决方案3】:

    如果描述该问题的其他答案不充分。
    您想要更改值的代码就是这些行

    test(&ptr);
    
    void test(int **tes){
        int *temp2 = new int;
        *tes =&temp2;
    }
    

    另外,不要乱用原始指针。 shared_ptr&lt;&gt;&amp; 可以成为你的朋友!

    【讨论】:

      猜你喜欢
      • 2022-01-09
      • 1970-01-01
      • 2019-08-22
      • 2019-02-27
      • 2020-10-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-06
      • 2017-03-24
      相关资源
      最近更新 更多