Search code examples
carraysalgorithmsortingselection-sort

Passing an array to a sort function in C language


#include<stdio.h>
#include<conio.h>

float smallest(int arr[],int k,int n);
void sort(int arr[],int n);

void main()
{
 int arr[20],i,n,j,k;
 clrscr();
 printf("\nEnter the number of elements in the array: ");
 scanf("%d",&n);

 printf("\nEnter the elements of the array");
 for(i=0 ; i < n ; i++)
 {
  printf("\n arr[%d] = ",i);
  scanf("%d",&arr[i]);
 }

 sort(arr,n);
 printf("\nThe sorted array is: \n");
 for(i=0 ; i < n ;  i++)
 printf("%d\t",arr[i]);
 getch();
}

int smallest(int arr[],int k,int n)//smallest function
{
 int pos=k,small=arr[k],i;
 for(i=k+1;i<n;i++)
 {
  if(arr[i]<small)
  {
   small=arr[i];
   pos=i;
  }
 }
 return pos;
}


void sort(int arr[],int n)//sorting function
{
 int k,pos,temp;
 for(k=0 ; k < n ; k++)
  {
   pos=smallest(arr,k,n);
   temp=arr[k];
   arr[k]=arr[pos];
   arr[pos]=temp;
  }
}

In the above program the sort function is being called from main but the return type of sort is void and it still returns the sorted array. As after sorting the array the function should return the sorted array back to the calling function to print the sorted array but the program runs perfectly. How is that happening?


Solution

  • When you declare

    int arr[20];
    

    you can say "arr is an array of 20 integers". But arr is a pointer to an integer as well, pointing to the first integer in a row of 20. So de-referencing *arr is an integer, the same as arr[0] in fact.

    This means when you pass arr to a function you only pass a pointer to that function. The function in this case works on the (copied) pointer. But this very pointer points exactly to the same memory as your original arr declared in main(). And that's the reason why manipulating arr in sort() is in fact manipulating arr in main().