0

I don't understand why the original array is sorted after calling the sorting function even though I used an alternate array. I first copied all the elements to avoid this problem. Any clarification would be welcome. Thank's.

#include <stdio.h>

void array_sort(int* t, int n)
{
    int min, index;
    int* p;
    for (int i = 0; i < n; i++) { //to avoid changing the original array
        *(p + i) = *(t + i);
    }
    for (int i = 0; i < n - 1; i++) {
        min = *(p + i);
        index = i;
        for (int j = i + 1; j < n; j++) {
            if (*(p + j) < min) {
                min = *(p + j);
                index = j;
            }
        }
        *(p + index) = *(p + i);
        *(p + i) = min;
    }

    for (int i = 0; i < n; i++)
        printf("%i\t", *(p + i));
}

int main(void)
{
    printf("Enter number of elements to be sorted : ");
    int n;
    scanf("%i", &n);
    printf("\nEnter the numbers : ");

    int p[n];

    for (int i = 0; i < n; i++) {
        scanf("%i", p + i);
    }

    array_sort(p, n);

    printf("\n");
    for (int i = 0; i < n; i++) { //check if original array is unsorted
        printf("%i\t", *(p + i));
    }

    return 0;
}
Younes
  • 17
  • 4
  • 6
    `int* p; for (int i = 0; i < n; i++) { *(p + i) = *(t + i); }`, this is clearly undefined behavior, and will not do what you expect. Maybe replace `int* p;` => `int p[n]` ? – Stargateur Jun 18 '17 at 02:02
  • The "sorting" part of this question isn't very relevant. You might want to narrow it so that you're just asking about how to make a copy of an array. – 4castle Jun 18 '17 at 02:04
  • 1
    You never allocated a second array in `array_sort`. – user2357112 Jun 18 '17 at 02:05
  • I'm just starting to learn about pointers so I may be wrong. Isn't int * p supposed to do that? – Younes Jun 18 '17 at 02:08
  • 5
    No; `int *p` allocates an uninitialized pointer that doesn't point to anything in particular. If you want it to point to some memory, you have to initialize it, either by making it point to some existing memory or by using `malloc()` to dynamically allocate some memory to use. Don't forget to free the memory when you're done with it. You're (un)lucky that your code ran and sorted the original array instead of crashing. – Jonathan Leffler Jun 18 '17 at 02:11
  • 2
    @lamriniyounes Read a book of C is mandatory to write C. `int *p`, just declare a pointer of `int` named `p`, his value is indeterminate, deference it is undefinde behavior. [The Definitive C Book Guide and List](https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) – Stargateur Jun 18 '17 at 02:12

1 Answers1

0

The behavior of the program will produce undefined behavior. The reason is the use of uninitialized pointer p in array_sort function. array_sort function will copy the array in some random memory as pointer p is not initialized.

Mostly this program will result in segmentation fault.

Darshan Prajapati
  • 843
  • 2
  • 11
  • 33