still the output is 10.... why? Though I am casting a to a pointer, how did it print??.... If I print only a, also results 10, pointer to a also results 10Code:int main() { int a = 10; printf("val = %lu",(unsigned long int*) a); return 0; }
still the output is 10.... why? Though I am casting a to a pointer, how did it print??.... If I print only a, also results 10, pointer to a also results 10Code:int main() { int a = 10; printf("val = %lu",(unsigned long int*) a); return 0; }
What you are doing results in undefined behaviour since the type of the argument is not correct. Therefore, the answer is: it printed like that because it was implemented to print that way. Something else could have been printed, or your compiler might even have refused to compile that.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
The above code (i.e. (unsigned long int*)a) does not make a pointer to a. The "(unsigned long int *)" is a cast - it converts the literal value you've given it into the type you say, so in this case it creates a pointer with value 10 (i.e. dereferencing the pointer would be an attempt to address byte number 10 on your system).
If you want a pointer to a, use "&a", which will have the type "int *" - I suggest you use "%p" as your format specifier in this case, i.e.:
Code:printf("val = %p", &a);
Last edited by JohnGraham; 10-09-2012 at 02:52 AM.
Programming and other random guff: cat /dev/thoughts > blogspot.com (previously prognix.blogspot.com)
~~~
"The largest-scale pattern in the history of Unix is this: when and where Unix has adhered most closely to open-source practices, it has prospered. Attempts to proprietarize it have invariably resulted in stagnation and decline."
Eric Raymond, The Art of Unix Programming