Question: I've written this code to sort an array using selection sort, but it doesn't sort the array correctly.

```
#include <cstdlib>
#include <iostream>

using namespace std;

void selectionsort(int *b, int size)
{
   int i, k, menor, posmenor;

   for (i = 0; i < size - 1; i++)
   {
      posmenor = i;
      menor    = b[i];
      for (k = i + 1; k < size; k++)
      {
         if (b[k] < menor)
         {
            menor    = b[k];
            posmenor = k;
         }
      }
      b[posmenor] = b[i];
      b[i]        = menor;
   }
}

int main()
{
   typedef int   myarray[size];
   myarray b;
   for (int i = 1; i <= size; i++)
   {
      cout << "Ingrese numero " << i << ": ";
      cin >> b[i];
   }

   selectionsort(b, size);
   for (int l = 1; l <= size; l++)
   {
      cout << b[l] << endl;
   }

   system("Pause");
   return 0;
}

```

I can't find the error. I'm new to C++.

Thanks for help.

Answer: 
The `selectionSort()` function is fine. Array init and output is not. See below.

```
int main()
{
    int size = 10; // for example
    typedef int myarray[size];
    myarray b;
    for (int i=0;i<size;i++)
//------------^^--^
    {
        cout<<"Ingrese numero "<<i<<": ";
        cin>>b[i];

    }

    selectionsort(b,size);
    for (int i=0;i<size;i++)
//------------^^--^
    {
        cout<<b[l]<<endl;
    }

    system("Pause");
    return 0;
}

```

In C and C++, an array with `n` elements starts with the `0` index, and ends with the `n-1` index. For your example, the starting index is `0` and ending index is `9`. When you iterate like you do in your posted code, you check if the index variable is less than (*or not equal to*) the size of the array, i.e. `size`. Thus, on the *last step* of your iteration, you access `b[size]`, accessing the location in memory next to the last element in the array, which is not guaranteed to contain anything meaningful (being uninitialized), hence the random numbers in your output.
You provided some sample input in the comments to your question.

I compiled and executed the following, which I believe accurately reproduces your shown code, and your sample input:

```
#include <iostream>

void selectionsort(int* b, int size)
{
    int i, k, menor, posmenor;
    for(i=0;i<size-1;i++)
    {
        posmenor=i;
        menor=b[i];
        for(k=i+1;k<size;k++)
        {
            if(b[k]<menor)
            {
                menor=b[k];
                posmenor=k;
            }
        }
        b[posmenor]=b[i];
        b[i]=menor;
    }
}

int main(int argc, char **argv)
{
    int a[10] = {-3, 100, 200, 2, 3, 4, -4, -5, 6, 0};

    selectionsort(a, 10);

    for (auto v:a)
    {
        std::cout << v << ' ';
    }
    std::cout << std::endl;
}

```

The resulting output was as follows:

```
-5 -4 -3 0 2 3 4 6 100 200

```

These results look correct. I see nothing wrong with your code, and by using the sample input you posted, this confirms that.