警告:赋值从整数生成指针而没有强制转换错误

时间:2015-05-10 21:49:27

标签: c arrays pointers

我正在做这个练习,我不得不写一个程序,它接收一个数字列表并交换数字对,以便它们按顺序排列:

void swapPairs(int* a[], int length)
{
   int i=0;
   int temp;
   while(i<(length-1))
   {
     if(a[i]>a[i+1])
     {
        temp=a[i];
        a[i]=a[i+1];
        a[i+1]=temp;
     }
     i++;
   }
}

int main()
{
  int array[]={2,1,3,1};
  swapPairs(array, 4);
  return 0;
}

我一直收到这些错误:

In function ‘swapPairs’:
warning: assignment makes integer from pointer without a cast
     temp=a[i];
         ^

warning: assignment makes pointer from integer without a cast
     a[i+1]=temp;


In function ‘main’: warning: passing argument 1 of ‘swapPairs’ from incompatible pointer type
swapPairs(array, 4);
         ^

note: expected ‘int **’ but argument is of type ‘int *’
void swapPairs(int* a[], int length)
  ^

当我尝试使用数组而不是指针时,它的效果非常好。有人可以解释这有什么问题以及如何解决它?
提前致谢。

2 个答案:

答案 0 :(得分:2)

您对swapPairs的声明是错误的 - 它不应接受int *int指针)的数组 - 它应该接受int的数组:

void swapPairs(int a[], int length)

答案 1 :(得分:1)

&temp;&#39; temp&#39;是int。 &#39; a [i]&#39;的类型是* int(指向int的指针)。

您正在分配指针的值而不是整数的值,因为您无法取消引用指针。

while循环应为:

    while(i<(length-1))
    {
        if(*(a[i])>*(a[i+1]))
        {
             temp=*(a[i]);
             *(a[i])=*(a[i+1]);
             *(a[i+1])=temp;
        }
        i++;
    }