Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers to int in c++ [closed]

What is wrong in that: I just wanted to pointers to int and give that ints value of 0.

    int* p;int* q;

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

This is annoying

WORKS:

int* p;
   *p = 0;

   cout<<*p<<endl;

CRASHES:

     int* p;
   int* q;
   *p = 0;
   *q = 0;

   cout<<*p<<endl;
like image 770
Yoda Avatar asked Nov 16 '25 20:11

Yoda


1 Answers

WORKS:

int* p;
*p = 0;

Nope! It appears to work, but is in fact undefined behavior.

Declaring int* whatever; leaves you with an uninitialized pointer. You can't dereference it.

To initialize a pointer & set the value it points to to 0 (in your case):

int* p = new int(0);
like image 185
Luchian Grigore Avatar answered Nov 19 '25 10:11

Luchian Grigore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!