Getting wrong output

rahulmaximus's Avatar, Join Date: Jun 2011
Go4Expert Member
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)
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
How large is the "large difference"?
What output do you get, and what output are you expecting?
rahulmaximus's Avatar, Join Date: Jun 2011
Go4Expert Member
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
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
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];
ptr++;
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.
Code:
(void*)(&str[3])-(void*)(&str[0])
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 like this
rahulmaximus's Avatar, Join Date: Jun 2011
Go4Expert Member
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