Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Getting wrong output (http://www.go4expert.com/forums/getting-wrong-output-t25975/)

rahulmaximus 4Jun2011 15:04

Getting wrong output


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])));

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)

xpi0t0s 5Jun2011 13:57

Re: Getting wrong output
How large is the "large difference"?
What output do you get, and what output are you expecting?

rahulmaximus 5Jun2011 23:41

Re: Getting wrong output
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.

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)


xpi0t0s 6Jun2011 03:38

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:

float *ptr=&str[0];

here ptr++ doesn't increment the pointer by 1 byte but by sizeof(float), so after the increment ptr is &str[1], which is far more use than &str[0]+1 byte, and saves you having to think of byte sizes all the time.

If you really want the difference to be 12 then you'll have to cast the pointer to something else.

might do the trick, or cast to char* instead, if you get an error about not knowing the size of what it's pointing at.

rahulmaximus 6Jun2011 20:36

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 02:29.