簡體   English   中英

為什么指針從 function 返回其先前的值

[英]why does pointer get its previous value returning from a function

伙計們,ptr如何獲得以前的價值? 代碼很簡單,我只是想知道為什么它不存儲在 function 中分配的地址值。

#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);


}

output 是:

function 內的指向 memory 的值: 710

function內部指針的值: 3405940

從 function 退出后,指向的 memory 的值: 3

從function退出后指針的值: 3406180

您按值傳遞了指針。

test內部的指針是main內部指針的副本 對副本所做的任何更改都不會影響原件。

這可能會造成混淆,因為通過使用int* ,您將句柄(“引用”,盡管實際上引用是 C++ 中存在的單獨事物)傳遞給int ,從而避免了該int的副本。 但是,指針本身本身就是一個 object,您通過值傳遞

(您還試圖將指針指向 function test本地的int 。使用它將無效。)

指針按值傳遞到 function,換句話說,它是由它制作的副本。 在 function 中,您更改了副本,但這不會改變 main 中的值。 如果要更改它,則需要使用指向指針的指針。

如果描述該問題的其他答案不充分。
您想要的代碼,以便您可以更改值是沿着這些行

test(&ptr);

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

或者,不要亂用原始指針。 shared_ptr<>&可以成為你的朋友!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM