[Solved] Why can’t we store addresses in normal int variables? and by assigning i dont want it to point anywhere.


why we need pointer variables…

No, we don’t need pointer variables until… we need one. In other words, there are many cases (or algorithms) which don’t need pointers. But soon or later you realize that pointers are needed.

Well, pointers contain values, which are different from integers, different from floating point numbers and so on. Even the space needed to hold such values can vary (an integer can take only 2 bytes, a float need more). An integer contains an (uh…) integer number, and only you (the programmer) know whether that number is correct or wrong. And a pointer contains an address and, again, only you know if that address is “correct” or not. A pointer “points” somewhere, there is nothing to do about it. There is an exception – normally, the value 0 or NULL is considered to “point nowhere”, but it is just an accepted convention.

That said, many languages do actually permit you to store a pointer into an integer variable or even stranger assignments, but the compiler, which already knows little about your intentions, in this case does know even less than before; so you have to force the compiler, for example using type casting, as you see in the other answer, and you must know what you are doing. A typical problem is, as already said in the comments, that sometimes pointers need more bytes than integers. It is the same scenario about converting a floating number to an integer: you know you will lose something (decimals, in this case). It happens that, if an integer variable has enough space (bytes for representing it), everything goes smoothly and you can store a pointer into an int, and back again; addresses are, in effect, integer values. But why you should do that? Only because your algorithm manages data coming out from something else than your program, for example a stream from outside world (data packets). Apart from this case, there are elegant (and correct) ways to keep well separated integers, and pointers, and mix them when needed (rarely).

solved Why can’t we store addresses in normal int variables? and by assigning i dont want it to point anywhere.