0
#include <stdio.h>

int* selectsort(int* ptr, int length);

int main()
{
    int array[] = {3, 4, 0, 2, 9, 6};
    int* ptr = array;
    int length = sizeof(array);
        // printf("%i\n", sizeof(*ptr));
    int* h = selectsort(ptr, length);
    for (int a = 0; a < length; a++)
    {
        printf("%i\n", *(h+a));
    }
    printf("hello\n");

}


int* selectsort(int* ptr, int length)
{
    int sortedarray[length];
    int* sorted = sortedarray;
    int smallest = 0;
    for (int i = 0; i < length; i++) {
            for (int z = 0; i < length; z++) {
                    if (*(ptr+i) > *(ptr+z)) {
                            smallest = *(ptr+i);
                    } else
                    {
                            smallest = *(ptr+z);
                    }
            } sortedarray[i] = smallest;
    }
    return sorted;
}

Hey there, somehow I'm getting a segmentation fault, but I can't find the error. Probably has to do something with memory... As you can tell I'm quite new to c so it would be very nice if someone could help me :D Thanks for your help!

  • `for (int z = 0; i < length; z++)` -- did you mean `z < length;`? – Fred Larson Feb 28 '20 at 23:00
  • 1
    Undefined behavior for using the value of a pointer to an object beyond the end of the object's lifetime. – EOF Feb 28 '20 at 23:00
  • 2
    `sizeof(array)` doesn't do what you think it does. – Fred Larson Feb 28 '20 at 23:10
  • `int length = sizeof(array);` should be `int length = sizeof(array) / sizeof(int);` –  Feb 28 '20 at 23:11
  • And there is more: you cannot return `int* sorted` since it points to an array whose lifetime ends with `selectsort` function. By the way, you don't need to declare a pointer to point to an array. –  Feb 28 '20 at 23:24

0 Answers0