Why can't we use direct addressing in c or c++ code?

c, c++, pointers

Solution

Because there is nothing in the C or C++ standard to guarantee that. Those addresses may be predictable depending your compiler/OS, but don't count on it.

#include <stdio.h>

int main(void) {
    char s[] = "okay";
    printf("%p", (void*)s);
    return 0;
}  

I get a different address every time (gcc on linux). Don't use "address literals" ;)

Process address space on modern OS's is randomized for security on each execution:

http://en.wikipedia.org/wiki/Address_space_layout_randomization

Problem

When I compile and execute this code consecutively for a couple of times, it reports the address of cc as 0x0012FF5C. But when I try to print out the string at that address using the second call to printf in foo, it prints garbage instead of printing out "Hello"?? Why so?? What's wrong if I directly paas the address as an argument when I know that the address lies within the address space of the application (atleast until I don't reboot my PC, or start some other application which requires a lot of space and which causes my application to be paged out)?? ``` void foo(char *cc[]) { printf("%x\n",cc); printf("%s\n",(char *)(0x0012FF5C)); } int main() { char *c[] = {"Hello","World"}; foo(c); } ```

Original source