主要指针仍然指向函数中的变量

时间:2017-10-20 11:34:35

标签: c pointers scope

#include <stdio.h>
#include <stdlib.h>

void changeAddressofPtr(int ** ptr);

int main()
{
    int num = 12;
    int * numptr = &num;//num pointer points to num variable

    printf("%d\n",*numptr);   //just a check
    changeAddressofPtr(&numptr);  //send address of pointer to be able to change it
    printf("%d",*numptr);  //check value after changing

    return 0;
}

void changeAddressofPtr(int ** ptr)
{
    int newNum = 8;
    *ptr = &newNum;  //make main's pointer point to newNum
}

我正在尝试这个,并期望在第二个printf()中打印错误或一些错误的垃圾值,但这是输出:

12
8 //Value of variable I thought would be deleted

0 个答案:

没有答案