Exchanging values between 2 variables
code runs but ide stops working... any ideas??
printf("Enter the values of a and b \n");
printf("After exchange values of a and b are %d and %d ",a[i],b[i]);
What's the value of i? It's garbage, which has a very high probability of not being either 1 or zero (the only valid values for an index into those two arrays). By accessing some memory location outside what was allocated for the arrays, you are overwriting something -- that's called clobbering and is a very insidious kind of bug.
Before you use a variable, remember to always initialize it. That is especially important with pointers, since using a garbage pointer will almost invariably result in you trying to access memory that's not yours resulting in the program crashing "for no reason" due to a segfault.
what should be correction in my code please tell
its done i used i=2; thanks :)
Comments on this post
Which is dead wrong.
Originally Posted by swapy
When you declare an array in C, you declare it with the total number of elements in that array. You wrote:
Thus both arrays contain two elements each.
The indexing of arrays in C is zero-based, which means that the first element is indexed with 0. That means that the second element is indexed with 1. The third element would be indexed with 2, but in your arrays there is no third element.
By setting i to 2, you are indexing outside of your arrays, thus clobbering the memory locations next to those two arrays. That is a very bad idea.
Always remember this basic rule: in an array of n elements, the indexes range from zero to n-1. Always!
January 22nd, 2013, 06:42 AM
rightly said... fixed it :)