What I am trying to do is to create a function that sorts an array given its length and a pointer to its head.
void Sort(int **arr, int len)
{
int ech = 1;
while (ech != 0)
{
ech = 0;
for (int i = 0; i < len - 1; i )
{
if (*(arr[i]) > *(arr[i 1]))
{
int temp = *(arr[i]);
*(arr[i]) = *(arr[i 1]);
*(arr[i 1]) = temp;
ech ;
}
}
}
}
And when I try to call it in my main in returns a code=3221225477 error.
int main()
{
int arr[10] = {100, 30, 100, 17, 11, 12, 7, 18, 200, 25};
Sort(&arr, 10);
// for (int i = 0; i < 10; i )
// {
// printf("%d ", arr[i]);
// }
return 0;
}
CodePudding user response:
When you look at the compiler warnings you see that you call Sort
with an incompatible pointer. &arr
is a pointer to array of int
, but your Sort
function wants a pointer to a pointer to int
. It works if you change your Sort
function to only take a pointer to int
.
void Sort(int *arr, int len)
{
int ech = 1;
while (ech != 0)
{
ech = 0;
for (int i = 0; i < len - 1; i )
{
if ((arr[i]) > (arr[i 1]))
{
int temp = (arr[i]);
(arr[i]) = (arr[i 1]);
(arr[i 1]) = temp;
ech ;
}
}
}
}
You call that function as Sort(arr, 10);
.
CodePudding user response:
If you set your compiler to show all warnings, it will progressively walk you through a couple of levels of issues, the first masking the second...
The first indication there is a problem is the compiler warning against line Sort(&arr, 10);
being called against your prototype void Sort(int **arr, int len)
:
warning: incompatible pointer types passing 'int (*)[10]' to parameter of type 'int **'
This should lead you to remove the address of operator &
, (and subsequently to remove the extra *
from void Sort(int **arr, int len)
The next compile attempt should now indicate that you've exposed errors lurking in Sort()
in the form of incorrect application of dereferences on the arr
variables; *(arr[i])
.
43, 17 error: indirection requires pointer operand ('int' invalid)
(repeats 5 times)
These are corrected by removing the dereference. i.e. change this: *(arr[i])
: to thisarr[i]
Corrections to your code: (see comments)
void Sort(int *arr, int len)//change prototype
{
int ech = 1;
while (ech != 0)
{
ech = 0;
for (int i = 0; i < len - 1; i )
{
if (arr[i] > arr[i 1])
{
int temp = arr[i];//remove all defreferenceing of arr
arr[i] = arr[i 1];
arr[i 1] = temp;
ech ;
}
}
}
}
int main(void)
{
int arr[10] = {100, 30, 100, 17, 11, 12, 7, 18, 200, 25};
Sort(arr, 10);//remove address of operator (arr is already a pointer)
// for (int i = 0; i < 10; i )
// {
// printf("%d ", arr[i]);
// }
return 0;
}