ERROR! Invalid conversion from const int* to int*!

closed account (jvqpDjzh)
/*
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
1
2
3
4
5
void foo( int const * a 
//&a[i] shouldn't be constant!

void bar( int * const a
//it's the same as above 

No. They are not the same.
closed account (jvqpDjzh)
/*
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)?
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.
closed account (jvqpDjzh)
'a' is a name of a pointer variable that points to a constant integer.

=>Although i thought that to define a constant integer we should first put the reserved word 'const' before the type...

Thank you!
That works too; int const * a is equivalent to const int * a.
Topic archived. No new replies allowed.