Tuesday, July 14, 2009

Studying for final, need help with c?

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


#define N 100





int main()


{


---int c, i = 0;


---char s[N];





---while((c = getchar()) != '\n' %26amp;%26amp; i %26lt; N)


------s[i++] = c;





---s[i] = '\0';


---printf("%s\n", s);





---return 0;


}





there are two bugs in this program, what are they?(hint: look for errors at the boundaries)





okay ive compiled this program and everything, i ant seem to figure out what the errors should be, i copied/pasted this directly from an old exam. Any help please

Studying for final, need help with c?
the while loop limits i to 99. however it will be incremented to 100 in s[i++]=c; s[N] is s[100], which i think in C means it can have element from s[0] to s[99]. So your array will be out of bounds when i=100.


also it seems like s[i]='\0'; overwrites the last entered character.
Reply:there is no bug in the program


the program prints what ever the input you give
Reply:while((c = getchar()) != '\n' %26amp;%26amp; i %26lt; N-2)


------s[i++] = c;


/*


i points to the last array element now, no "out-of-bound" errors.


*/


No comments:

Post a Comment