Friday, July 31, 2009

Why the output of printf("%d %d",a,*a) is 1 0 ?

when *a=1 and integer in c programing..

Why the output of printf("%d %d",a,*a) is 1 0 ?
make sure 'a' is defined as a pointer to another variable you've declared. like:





int b = 1;


int* a = %26amp;b;





Otherwise, if you simply declare


int* a;


*a = 1;





..then you have reserved memory for an address, but not for the contents. 'a' is pointing to a pseudo-random place in memory.





Secondly, printf() of 'a' should return the address you've reserved. printf() of '*a' should return the 1 as you're expecting. The most likely reason you're not seeing this is because 'a' is set to (1) - which means it is not a valid pointer. This can be caused by some compilers in a DEBUG build when a variable goes out of scope. As in:





int* a;


{


int b = 1;


a = %26amp;b;


}


// 'b' is now out of scope - some compilers will change memory to indicate this during a debug build. *a is now (0) !





Hope that helps.
Reply:could you more explain for me?Thank you Report It

Reply:it is wrong output ,


your output should be


value of 'a' and , value at 'a'


ie. (some memory address) , 1





recheck your code

potential breakup song

No comments:

Post a Comment