user6521303
user6521303

Reputation:

What happen if assign constant value to int pointer?

If I have assign constant value to int pointer then what is happened internally?

Like, int *p = 5;

Then what is a value if I have print *p and p and Why?

Upvotes: 2

Views: 82

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409176

If you have

int *p = 5;

you have a variable p that is pointing to the address 5. There will most likely not be a valid int value at that address. Dereferencing the pointer will most likely lead to undefined behavior. Writing to the memory will most likely cause a crash, and as it is unaligned reading it might cause a crash too on some systems that don't allow unaligned reads.

Doing like that is valid in some situations, which is why it's allowed. Think for example small embedded systems with a fixed memory map, where certain "registers" are stored at some fixed address. Then you can make a pointer and make it point directly at that address.

Upvotes: 4

Marievi
Marievi

Reputation: 5011

The declaration

int *p = 5;

means that you create a pointer to an integer and you assign the value 5 to its content. In other words, you make pointer p point to the memory address 5, where you do not know if there will exist a valid integer value.

  • If you print *p, you actually print the content of the pointer, or in other words the value of the integer where p points to.
    • If you print p, you actually print the address of pointer p, in other words the memory address where p is stored.

Upvotes: 1

Related Questions