1

Why the changes I applied to the a[] in selection_sort function will also applied to series[] in the main function? Can anyone explains this to me?

#include <stdio.h>
#define NUMS 8

void selection_sort(int a[], int n);

int main(void)
{

    int i, series[NUMS];

    printf("\nEnter %d numbers: ", NUMS);
    for (i = 0; i < NUMS; i++)
        scanf("%d", &series[i]);

    selection_sort(series, NUMS);

    printf("Sorted: ");
    for (i = 0; i < NUMS; i++)
        printf("%d ", series[i]);
    printf("\n\n");

    return 0;
}

void selection_sort(int a[], int n)
{

    if (n == 0) return;

    int i, li = 0;

    for (i = 1; i < n; i++)
        if (a[i] > a[li])
            li = i;

    i = a[n-1];
    a[n-1] = a[li];
    a[li] = i;
    selection_sort(a, n - 1);
}

I expect that changes in a[] array can't interfere the elements inside series[]. But this confuse me.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
Blue
  • 385
  • 3
  • 11
  • `a` is not an array. – melpomene Aug 26 '19 at 05:27
  • 1
    The parameter `a` will resolve to a pointer when compiled. So when you pass `series` to `selection_sort` you are actually passing the address of where `series` is in memory. – andresantacruz Aug 26 '19 at 05:29
  • @dedecos May I know why this only happen to array only? – Blue Aug 26 '19 at 05:34
  • http://c-faq.com/aryptr/aryptrparam.html – melpomene Aug 26 '19 at 05:40
  • 1
    When calling the function using the array name, you are actually giving the address of first element in the array. So instead of making copy of your array, compiler will pass the address of original array `series[]`. So any edit will go to the value pointed by the address, i.e. the original array. – Mhmd Az Aug 26 '19 at 05:44
  • @MarcoBonelli Yes, I saw that and I ment that. From the title we already assumed that some kind of misunderstanding of array assignment exists. And so it is. – the busybee Aug 26 '19 at 05:52
  • @thebusybee that title was the perfect example of a bad title. No context and not a single indication about what the problem is about. Also using random variable names, which basically creates a question that will never be hit in search results, making it almost useless. – Marco Bonelli Aug 26 '19 at 05:55
  • Related: https://stackoverflow.com/questions/1461432/what-is-array-decaying – user3386109 Aug 26 '19 at 06:05

1 Answers1

2

Your elements are being manipulated because when you pass an array to a function, that array is treated as a pointer pointing to the base location of the array, hence manipulating your elements

arvind
  • 275
  • 2
  • 11
  • Reference: [C11 Standard - 6.3.2.1 Other Operands - Lvalues, arrays, and function designators(p3)](http://port70.net/~nsz/c/c11/n1570.html#6.3.2.1p3) – David C. Rankin Aug 26 '19 at 05:57