2015-02-10 56 views
0

我想使用數組的指針進行選擇排序。使用指針進行選擇排序

void sort(int size, int *ptr) 
{ 
int temp; 
bool swap; 
do 
{ 
    swap = false; 
    for (int count = 0; count < (size - 1); count++) 
    { 
     if (*ptr[count] > *ptr[count + 1]) 
     { 
      temp = *ptr[count]; 
      *ptr[count] = *ptr[count + 1]; 
      *ptr[count + 1] = temp; 
      swap = true; 
     } 
    } 
} while (swap); 
} 

即時獲取很多錯誤說非法的方向,因爲當使用*它必須是一個指針。我在其他方法中使用它,只是它有這個麻煩。這是我正在使用的電話。

sort(arraySize, numArray); 

一切都是在其他方法中聲明和使用的。

+1

這行你看到錯誤消息?也可能應該是'ptr [count]'而不是'* ptr [count]'。 ptr是一個指針而不是一個指針數組。 – 2015-02-10 05:04:51

+0

修復它謝謝! – BucketsOstuff 2015-02-10 05:07:11

+0

所以將'* ptr [count]'改爲'ptr [count]'。如果使用數組下標,則不需要取消引用指針。在大多數情況下,指針可以用*運算符或數組下標來取消引用。 – 2015-02-10 05:10:12

回答

0

錯誤在*ptr[count] 這是錯誤的指針解引用語法。

ptr[count]*(ptr + count)

0

這裏的編譯錯誤刪除的版本。

void sort(int size, int *ptr) 
{ 
int temp; 
bool swap; 
do 
{ 
    swap = false; 
    for (int count = 0; count < (size - 1); count++) 
    { 
     if (ptr[count] > ptr[count + 1]) 
     { 
      temp = ptr[count]; 
      ptr[count] = ptr[count + 1]; 
      ptr[count + 1] = temp; 
      swap = true; 
     } 
    } 
} while (swap); 
} 
1

使用ptr[]代替*ptr[]因爲, ptr是指針並且如果與[]使用則在該位置處狀陣列確實返回元件。

void sort(int size, int *ptr) 
{ 
int temp; 
bool swap; 
do 
{ 
    swap = false; 
    for (int count = 0; count < (size - 1); count++) 
    { 
     if (ptr[count] > ptr[count + 1]) 
     { 
      temp = ptr[count]; 
      ptr[count] = ptr[count + 1]; 
      ptr[count + 1] = temp; 
      swap = true; 
     } 
    } 
} while (swap); 
} 
0

這是正確的結構 而使用數組的指針符號不得使用*,使用指針的名字沒有「*」 itslef指0指數指針數組的

void sort(int size, int *ptr) 
{ 
int temp; 
bool swap; 
do 
{ 
    swap = false; 
    for (int count = 0; count < (size - 1); count++) 
    { 
     if (ptr[count] > ptr[count + 1]) 
     { 
      temp = ptr[count]; 
      ptr[count] = ptr[count + 1]; 
      ptr[count + 1] = temp; 
      swap = true; 
     } 
    } 
} while (swap); 
}