Friday, May 21, 2010

Epxplain me pls C++ function.?

#include%26lt;stdio.h%26gt;


main()


{int mas[5]={0};


int *p;


int i;


p=mas;


system("cls");


i=0;


do


{


*(p+i)=i;


printf("\n mas[%d]=%d",i,*(p+i));


i++;


}while(i%26lt;5);


}








So my question is: why can`t i++ be BEFORE printf??? it turns in some garbage when i try to put it before printf. Eplain to me pls.

Epxplain me pls C++ function.?
You did not initialize the whole mas array. You only initialize the first element to 0. So if you i++ before print, you are point to the next element which has not been initialized.
Reply:First of all, this is C code, not C++.





By incrementing i before the printf statement you're exceeding array bounds at the end of the statement where you're dereferencing the pointer : *(p+i)





Think about it. At some point you'll get to where i == 5 and that's where the problem occurs. Because this is a do..while construct, the index out of bounds won't be caught.





Additionally it's better to write *(p + i) as p[i]. And if you think hard about it you'll see that p[i] is the same as i[p].


No comments:

Post a Comment