指向c++中int的指针

Pointers to int in c++

本文关键字:指针 int c++ 指向      更新时间:2023-10-16

这有什么错:我只是想指向int,并给int值0。

    int* p;int* q;
*p = 0; *q = 0;
cout<<"p = "<<*p<<" q = "<<*q<<endl;

这是令人讨厌的

作品:

int* p;
   *p = 0;
   cout<<*p<<endl;

崩溃:

     int* p;
   int* q;
   *p = 0;
   *q = 0;
   cout<<*p<<endl;
WORKS:
int* p;
*p = 0;

它看起来有效,但实际上是未定义的行为。

声明int* whatever;会留下一个未初始化的指针。你不能取消引用它。

初始化指针&将它指向的值设置为0(在您的情况下):

int* p = new int(0);

要使用指针,指针必须指向某个东西。所以有两个步骤:创建指针,并创建它指向的东西

int *p, *q;    // create two pointers
int a;         // create something to point to
p = &a;        // make p point to a
*p = 0;        // set a to 0
q = new int;   // make q point to allocated memory
*q = 0;        // set allocated memory to 0

您没有为指针分配任何内存,所以您得到了未定义的行为。基本上,这意味着任何都可能发生(包括它也会起作用的可能性)。

使用int something = new int(<initialization_value>);初始化指针。