當我嘗試運行該程序時,收到消息。爲什麼?僅使用while對數組進行排序
Segmentation fault
我的代碼:
#include <stdio.h>
void sort_array(int *arr, int s);
int main() {
int arrx[] = { 6, 3, 6, 8, 4, 2, 5, 7 };
sort_array(arrx, 8);
for (int r = 0; r < 8; r++) {
printf("index[%d] = %d\n", r, arrx[r]);
}
return(0);
}
sort_array(int *arr, int s) {
int i, x, temp_x, temp;
x = 0;
i = s-1;
while (x < s) {
temp_x = x;
while (i >= 0) {
if (arr[x] > arr[i]) {
temp = arr[x];
arr[x] = arr[i];
arr[i] = temp;
x++;
}
i++;
}
x = temp_x + 1;
i = x;
}
}
我認爲這個問題是在if
聲明。 你覺得呢?爲什麼會發生?我認爲我以積極的方式使用指向數組的指針。
謝謝!
'我'會太大,並導致超出範圍的訪問,它調用*未定義的行爲*。 – MikeCAT
使用-g編譯程序並在gdb下運行,這會告訴你它失敗的位置 – pm100
嘗試使用[冒泡排序](https://en.wikipedia.org/wiki/Bubble_sort)方法(就像使用了[這裏](http://www.sanfoundry.com/c-program-sort-array-ascending-order/)按升序對數組進行排序) – iRove