+ 1

Can two VARIABLES (not POINTERS) have same Memory Location in the memory?

Both the variables are in the same scope and have same memory location due to limited available memory.

7th Oct 2018, 1:25 PM
Abhimanyu Gupta
Abhimanyu Gupta - avatar
4 Antworten
+ 3
If you have two variables "int a,b;" and there is not enough memory to give them each separate locations, the program will die.
7th Oct 2018, 3:35 PM
John Wells
John Wells - avatar
+ 2
Yes union do the same thing. But this will continue till you give the value to the variable. only declaration of the variable can be on same location.
7th Oct 2018, 1:35 PM
BALOOCH ANZARAHMEDKHAN ZAKIRAHMEDKHAN
BALOOCH ANZARAHMEDKHAN ZAKIRAHMEDKHAN - avatar
+ 1
OP, I think you misunderstand _what_ a variable fundamentally is... A variable _is_ a memory address. At least given a human-readable and constant name. See, put simply (very simply), for each variable, your program asks the host (directly the OS or VM/interpreter which then asks the OS in turn), "Gimme a free address that has at least X bytes unallocated space following it." (which is why I used the term 'host', it's broad enough). Anyhoo, once that address is given, the OS marks it and the following X bytes "allocated / in use". Even pointers work this way, they just happen to _store_ memory addresses (uint64 normally today). So a ptr on 64bit arch will usually be the size of an unsigned 64bit int AFAIK. It's hard to think of a computer in these terms, without the magic of the layers of abstraction (for user, coder, or sysadmin). In the end, though, it's just a crude machine (ignoring recent advances in quantum tech). Hope this demystifies things... [1/2]
7th Oct 2018, 4:01 PM
non
+ 1
[2/2] ... As for unions, they're not two variables occupying the same address -- at least not at the same time. A union is a special struct and somewhat of a cunning trick. I'll leave you with this stock explanation as it probably explains it better than I could: https://en.m.wikipedia.org/wiki/Union_type
7th Oct 2018, 4:08 PM
non