![]() |
Getting wrong output
hello
#include<iostream> using namespace std; int main() { float str[]={1.1,2.2,3.1,4.1,5.4,6.4,7.12,8.3}; printf("%d", ((&str[3])-(&str[0]))); printf("\nand the otr is %d",&str[0]); printf("\nand the otr is %d",&str[3]); printf("\nand the otr is %d",((&str[3])-(&str[0]))); system("pause"); } well the problem is that.....&str[3] &str[0]....have large differnce between them .....but still thr minus is giving only 3(as in it is treating it as the characters) |
Re: Getting wrong output
How large is the "large difference"?
What output do you get, and what output are you expecting? |
Re: Getting wrong output
hello
my query 1.well the addressing pattern of an(int) array leavse spaces of 2 between consecutive elements. 2.simlary for the float it is 4 difference since the size of the block is 4. 3.Now since here i m displaying the differences of the address of the two..(i m expecting 3*4(where 4 is the size of the float->that is 4) 4.but the output of the difference is coming out to be 3.....(which i think shud only be thr wen it is char array) 5.Int all three cases of array (int)(float)(char)..i get 3..which is vague. Observation-----> Even when u see the output of.... printf("\nand the otr is %d",&str[0]); and printf("\nand the otr is %d",&str[3]); we can clearly observe thr is a deifference of 12 in the address of the 2... but wen printf("%d", ((&str[3])-(&str[0]))) in the earlier printf is done i get 3...not 12(this is wwht i a not getting) Regards Rahul |
Re: Getting wrong output
Pointer arithmetic takes the size of what's being pointed to into account. So you get 3 because 12 bytes at 4 bytes per float is 3 floats.
You get the same effect if you do: Code:
float *ptr=&str[0];If you really want the difference to be 12 then you'll have to cast the pointer to something else. Code:
(void*)(&str[3])-(void*)(&str[0]) |
Re: Getting wrong output
yes,thank..i was thinking in that way only..i used tycasting itself in the end
(int)&str[3])-(int)(&str[0] which gives the result ...Thank u anyways :) |
| All times are GMT +5.5. The time now is 07:08. |