C pointers : What will be the output?
Hey,
I guess the topic is self explanatory Quote:
Quote:
Note I knw the outputs I have compiled in GCC and executed. Tell me what they mean and why is that the output? |
Code:
printf("%d",&i); |
That one I knew. I am wondering abt the scanf thing . That could lead to anything. Sometimes runtime errors sometimes not. Why? If possible could anyone tell me what kind of int values are good as memory addresss?
|
Code:
scanf("%d",i); |
Code:
// Wrong Code:
#include <stdio.h> |
Dude, I also knw thats wrong. I am asking what will be the output. My GOD!!! you thought you had to teach how to use scanf and printf???
Anyways , could anyone tell me what values of integer i would be okay if they are used as memory addresses thru scanf("%d",i); |
Quote:
Quote:
|
No I am not setting it. I am generally asking for the fun of it.
Right now the second program in 1st post compiles and works. Sometimes gives a runtime error though. I guess thats bcos C gives a garbage value to newly declared int unlike Java. What I wanted to know was what range of ints wouldn't give a runtime error? |
You weren't very specific the first time. Now I got it. You're basically asking what memory addresses would be available to store an int when you call that program. Unfortunately I can't answer that question [don't even know if you can correctly predict those address values].
|
The first program consistenly outputs 1120403456, which is as you guessed the IEEE 754 single precision representation of the number 100.
Code:
1120403456 |
Quote:
|
Quote:
p is a pointer to a float, and this float is set to 100. Quote:
Quote:
|
I was looking at *p=100; but i was mistaken so nevermind :p
|
The example code orders the computer to set 'p' to the address of 'i' and to treat that pointer as "a pointer to a float value," which it obligingly does.
It then orders to store the floating-point number "100.0" into the location pointed-to by 'p', which again it obligingly does. Notice that if 'i' is too small to contain a float, it won't matter: the computer will still store the value in memory as ordered, thus destroying whatever's in those "extra" locations. (A most serious bug.) The final statement orders the computer to display the value of 'i', which will now contain the binary value equivalent to [the leading bytes of] the floating-point number '100.0.' A far more desirable method to do such a thing is with the union directive, which stipulates that all of the variables in the union begin at the same address. The size of the union is the size of the largest member. Thus: Code:
union { Quote:
|
Quote:
Code:
union { |
All times are GMT -5. The time now is 05:22 PM. |