Mar 11, 2014 at 12:27pm UTC
/*
Why the compiler of dev-cpp gives this error?
What it is the solution?
*/
/******************************************************************************/
void selectionSort(int const *a, const int len)
{
int smallest=0;//contains the smallest element of the rest portion of the array
for (int i=0; i<len-1; i++)
{
smallest=i;
for (int j=i+1; j<len; j++)
{
if(a[j] < a[smallest])
smallest=j;
swap(&a[i], &a[smallest]);//ERROR! invalid conversion from const int* to int*! //&a[i] shouldn't be constant!
}
}
}
/******************************************************************************/
//the parameters have to receive an address, thus swap can modify directly the values in selectionSort!
void swap(int * const a, int * const b)//swap the position of a[i] and a[smallest]
{
int hold = *a;
*a = *b;//moves the smallest element to the first position of the array
*b = hold;
//it's the same as above
//int hold = a[i];
//a[i] = a[smallest];
//a[smallest] = hold;
}
/******************************************************************************/
int main()
{
...
}
Last edited on Mar 11, 2014 at 12:28pm UTC
Mar 11, 2014 at 1:07pm UTC
/*
int hold = *a;
*a = *b;//moves the smallest element to the first position of the array
*b = hold;
//it's the same as above!!!
//int hold = a[i];
//a[i] = a[smallest];
//a[smallest] = hold;
*/
So what means the first heading of the function (int const * a)?
Mar 11, 2014 at 1:40pm UTC
Declarations should be read from right to left.
'a' is a name of a pointer variable that points to a constant integer.
vs
'a' is a name of a constant pointer variable that points to an integer.
Mar 11, 2014 at 2:24pm UTC
That works too; int const * a
is equivalent to const int * a
.