简体   繁体   中英

Can I initialize a value to a pointer?

int *p;
*p=100;
cout<<*p;

Is this correct or it should give some error?

This will invoke undefined behaviour ; you are dereferencing an uninitialised pointer. However, your code may "work", as that's one possible outcome of undefined behaviour.

Neither.

It is not correct, but the C (or C++) standard places no requirement on the implementation that it should give any error.

Certain things in C (or C++) are "undefined behavior", meaning that the standard doesn't care what happens. This is one of them. The implementation might make some effort to tell you that something is wrong, but it is not required to. It is your responsibility (as the programmer) to avoid undefined behavior.

Syntactically looks ok, but of course you can find out what happens by simply running it.

However, consider that you are storing a value in a location that is unknown (we don't know where p is pointing) hence the resulting behavior is unknown (ie undefined behavior ) too.

You need to allocate some space for the interger.

ie

int *p = new int;
*p = 100;
cout << *p;
delete p;

It is wrong.

The primary value which a pointer holds is the address of the memory location that it is pointing to.

The statement int *p, defines p as the pointer.

It has to be initialized by pointing to a variable, lets say x.

After initialization, printing p will give you the memory address of x and printing *p will give you the value that x is holding.

It may perform some function, but definitely wont serve your purpose.

This writes to whatever location the uninitialized variable p points to, so it may or may not work (if it does don't think it's ok - it's not!) due to undefined behaviour. Most likely it will crash your program.

A good compiler with the proper options (eg gcc's -Wall ) will show a warning:

warning: 'p' is used uninitialized in this function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM