全局指针和本地指针有什么区别?

Sha*_*han 0 c c++ pointers global-variables

我有一个像这样的小代码:

 #include <stdio.h>

    int *ptr1;
    int *ptr2;


  void some_function(void)
    {

    int B = 5;
    ptr2 = &B;
    }

  main (){
    int C, D;
    int A =10;
    int *ptr3;
    ptr1= &A;

    ptr3=ptr2;

    some_function();

    C = *ptr1 + *ptr2;

    printf("Sum of the numbers C= %d\n",C);

    some_function();
    D = *ptr1 + *ptr3;

    printf("Sum of the numbers D= %d\n",D);

  }
Run Code Online (Sandbox Code Playgroud)

为什么我不得到D的结果但得到C的结果?我得到了print语句S的结果,um of the numbers C=15但是对于D的最后一个print语句没有任何结果.本地和全局指针之间有什么区别(我的意思是ptr1和ptr2都是全局定义的,而ptr3是定义本地的)?指针赋值是否ptr3=ptr2有效?指向局部变量Vs的指针是否有任何显着差异?指向全局变量的指针?

oua*_*uah 7

ptr3 = ptr2;
Run Code Online (Sandbox Code Playgroud)

ptr3被初始化为值ptr2是NULL.这是NULL因为您没有初始化它并且它具有静态存储持续时间.

然后你做

D = *ptr1 + *ptr3;
Run Code Online (Sandbox Code Playgroud)

您正在取消引用ptr3哪个是空指针:这是未定义的行为.ptr2在您的程序中,值可能已更改,但ptr3仍为空指针.

编辑:为了完整性(好吧,有点):

void some_function(void)
{
    int B = 5;
    ptr2 = &B;
}
Run Code Online (Sandbox Code Playgroud)

B当函数some_function退出时,对象生存期结束.您不能访问B通过ptr2后,some_function又回来了.它的意思是:

C = *ptr1 + *ptr2;
Run Code Online (Sandbox Code Playgroud)

还会调用未定义的行为,因为您ptr2在此语句中取消引用哪个是无效指针.