"Radhika Sambamurti" <(EMail Removed)> wrote in message
news:(EMail Removed) rg...
> Hi,
> I'm a relative newbie....
>
> I've written a program to do a bubble sort. take in numbers and sort them.
> My question is: at the very end of the sort() function, when I have to
output the result to stdout, the only code that does this correctly is as
follows:
> //output of sorted array
>
> for(i=1; i<n+1; i++)
> {
> cout << "value of i is: " << num_array[i] << endl;
> }
>
> }
>
> When i tried saying  for(i=0; i<n; i++),
> the zero'th element was some hex garbage (being the address of the array i
assume) and only sub[1,2,3,4] were output. So why does num_array[0] give me
hex? I used gdb to debug this, but this just verifies my findings. I would
like to know why.
>
> Thank you,
> Radhika
>
> /////Code below//////////////////////////
>
> //Sorting in ascending
> #include <iostream>
> using namespace std;
>
> const int SIZE= 5;
> void sort(int number[], const int SIZE); //prototype never takes array
size
> int main()
> {
> int number[SIZE] = {49,19,23,69,7};
>
> sort(number, SIZE); //Function call with array
> //always only array name
> return 0;
> }
>
> ///////// Function sort()
>
> void sort(int num_array[SIZE], const int n)
> {
> int temp, i;
>
> for(int k=0; k<n; k++) // outer loop
> {
> for(int j=0; j<n; j++) //inner loop
> {
// didn't analize it too much, but
// when j == n1 then j + 1 below is 1 past the end of array
// see what you can do about it
// then see if the problem persists
> if(num_array[j] > num_array[j+1])
> {
> temp = num_array[j];
> num_array[j] =num_array[j + 1];
> num_array[j + 1] = temp;
> //swapping the variables to make
> //into ascending order
>
> }
> }
> }
>
> //output of sorted array
>
> for(i=1; i<n+1; i++)
> {
> cout << "value of i is: " << num_array[i] << endl;
> }
>
> }
>
after accessing memory past the array limit, anything can happen
Dan
