Tuesday, July 28, 2009

Void main() { int a[1],i; for(i=0;i<10;i++) {cin>>a[i];} for(i=0;k<10;i++) { cout<<"\t"<<a[i];} }//end

if we enter 1,2,3,4,5,6,7,8,9,10 in this program then it gives output 1,2,3,4,5,6,7,8,9,10.But Why?


I know that there is no array bound checking in c and cpp then why this is the output and if so then why we need to give the size of an array?


Please answer this question......................plz


Sourabh Jain,Amol Jore


M.C.A.,pune

Void main() { int a[1],i; for(i=0;i%26lt;10;i++) {cin%26gt;%26gt;a[i];} for(i=0;k%26lt;10;i++) { cout%26lt;%26lt;"\t"%26lt;%26lt;a[i];} }//end
Local variables are allocated on the stack. When you access past the end of the array you are trashing parts of memory that have been allocated for other things. To see this in action, change your variable allocation to this:





int j=0, a[1], i;





Now run your program again, but this time also print out the value of j. You'll see that j has been written over and is now holding one of the values you entered.
Reply:Well, isn't that what you'd expect if the array was properly dimensioned? You read ten elements into the array, then you output them in the same order (FIFO). Assuming the array can hold them, that is what you get (unless the error crashes the program or messes something else up).





When the array is too short, the excess (over-indexed) elements are stored into whatever happens to be next in memory (or on the stack). If those bytes are not used for anything important, the program may continue to behave the way you expect; if they are used for something important, your program may behave weirdly and/or crash. (There is no way to predict what will happen, in general, unless you know where everything is located in memory, on a particular machine.)





You need to give the size of the array


because anything outside those bounds


will clobber other stuff in memory.


(Since there is no way, in general, to predict what is where in memory, that makes the program "processor dependent" as well as "non-standard-conforming" -- which technically means that the processor may do whatever it wishes.)





----








There is an error in the code you gave, above.


The second loop has a condition "k%26lt;10" but the variable "k" is not declared.


Perhaps you meant to change all of the other instances of "i" to "k", including the "int" at the beginning.





Also, your code has a tab between each output value,


but the output you show uses commas.





Also, please do not put the code all on one line.


Yeah, I know computer don't care about whitespace.


But I do.


Remember that a programming language has TWO audiences: computers and people. Be more kind to the latter -- especially when asking questions.





void main() {


int a[1],i;


for(i=0;i%26lt;10;i++) { cin%26gt;%26gt;a[i]; }


for(i=0;k%26lt;10;i++) { cout%26lt;%26lt;"\t"%26lt;%26lt;a[i]; }


}//end


No comments:

Post a Comment