Simple Question

This topic is 4763 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hey everyone, I have a quick question about arrays. Suppose I have the code float f[2]; f[0] = 10; f[1] = 20; for(int i = 0 ; i < sizeof(f); i++) cout << f[i] << endl; return 0; I am guessing I am supposed to only get two lines of output... but im getting eight for some reason.. the first two are right but the rest are garbage values and such.. is there an explanation for this? Thanks!

Share on other sites
Yes, sizeof(f) = ( sizeof(float) * 2) = 4 * 2 = 8
Instead what you need to do is: i < 2 instead of sizeof(f).

Sizeof tells the memory size - not the physical array count.

Share on other sites
for(int i = 0; i < sizeof(f)/sizeof(f[0]); ++i)
This is only possible with arrays, not with pointers.