2015-02-10 93 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); 
}