userrandomnums userrandomnums - 1 month ago 4
C Question

Array and type/value errors in sorting function

I'm getting various errors and warnings that I don't understand.


  • error: "subscripted value is neither array nor pointer nor vector" in the top two functions with the arrays

  • warning: passing argument 1 of ‘SelectionSort’ makes integer from pointer without a cast
    int s = SelectionSort(arr, len);

  • note: expected ‘int’ but argument is of type ‘int *’: void SelectionSort(int arr, int len) {

  • error: void value not ignored as it ought to be: int s = SelectionSort(arr, len);



It sounds like they're simple fixes but types and values are my weak point! Any pointers? (pun unintended)

int find_maxind(int arr, int len) {
if(len == 1) return 0;
int ind = find_maxind(arr,len-1);
return (arr[ind] > arr[len-1])?ind:len-1;
}

void SelectionSort(int arr, int len) { //this cannot change
if(len <= 1) return;
int max_ind = find_maxind(arr,len);
int temp = arr[max_ind];
arr[max_ind] = arr[len-1];
arr[len-1] = temp;
SelectionSort(arr, len-1);
}

int main(){ //testing the sorting
int arr[] = {1,2,3,4,5,6,7,8,9,11,13,15,17};
int len = 13;
int s = SelectionSort(arr, len);
}

Answer

Complete working code.

int find_maxind(int arr[], int len) {
if(len == 1) return 0;
int ind = find_maxind(arr,len-1);

return (arr[ind] > arr[len-1])?ind:len-1;
}

void SelectionSort(int arr[], int len) { //this cannot change
     if(len <= 1) return;
     int max_ind = find_maxind(arr,len);
     int temp = arr[max_ind];
     arr[max_ind] = arr[len-1];
     arr[len-1] = temp;
     SelectionSort(arr, len-1);
}

int main(){ //testing the sorting
     int arr[] = {1,2,3,4,5,6,7,8,9,11,13,15,17};
     int len = 13;
     SelectionSort(arr, len);
}

Basically your program needs some changes:

 int find_maxind(int arr, int len) to int find_maxind(int arr[], int len)

 void SelectionSort(int arr, int len) to void SelectionSort(int arr[], int len)

Because you're passing arr in SelectionSort(arr, len);

I hope you got the answer.

Comments