Tuesday, July 5, 2022

[FIXED] why the array is sorted from other function in pass by value mode?

Issue

the problem is the x array is sorted correctly from other function in pass by value mode

and as per my understanding the array can't be sorted from other function in pass by value mode, it only sorted if i do pass by reference and i didn't , also the BubbleSort parameters they are just copy of the orignal variables so when the function finish ,the copy variables doesn't effect the original variables in main function,any explanation why and thanks.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

void BubbleSort(int a[])
{
  int temp=0;
  for(int i=0;i<10-1;i++)
    {
      for(int j=0;j<10-1;j++)
        {
          if(a[j]>a[j+1])
          {
            temp=a[j];
            a[j]=a[j+1];
            a[j+1]=temp;
          }
        }
    }
}
int main()
{
  int x[11]={7,6,4,5,8,11,14,37,2,9};
  BubbleSort(x);
  for(int i=0;i<10;i++)
    {
      printf("%d\n",x[i]);
    }
}
  

Solution

Arrays do not have the assignment operator.

In this function call

BubbleSort(x);

the argument expression having an array type is implicitly converted to pointer to its first element.

On the other hand, a function parameter that has an array type is implicitly adjusted by the compiler to pointer to the array element type.

Thus this function declaration

void BubbleSort(int a[]);

is adjusted by the compiler to the declaration

void BubbleSort(int *a);

So in fact elements of the array x declared in main are passed by reference through a pointer to the first element of the array. Using the pointer arithmetic the function has a direct access to each element of the original array passed to the function.



Answered By - Vlad from Moscow
Answer Checked By - Pedro (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.