【问题标题】:warning: assignment makes pointer from integer without a cast error警告:赋值从整数生成指针而没有强制转换错误
【发布时间】:2015-05-10 21:49:27
【问题描述】:

我正在做这个练习,我必须编写一个程序来接收一个数字列表并交换成对的数字,以便它们按顺序排列:

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)
  ^

当我只用一个数组而不是一个指针来尝试它时,它工作得非常好。有人可以解释一下这有什么问题以及如何解决吗?
  提前致谢。

【问题讨论】:

  • int* a[] 将其更改为 int a[]

标签: c arrays pointers


【解决方案1】:

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

void swapPairs(int a[], int length)

【讨论】:

  • 我的问题有两个部分;首先,我必须用 int a[] 作为参数来编写它,然后说明如果参数是 int* a[],我将如何更改它。这就是我坚持的部分
  • @ajia 巧合的是,您在发布的问题中遗漏了部分。我们不是读心者。
  • @ajia int *a[] 不是您在问题中所说的“数字列表”。如果您显示将使用 int *a[] 调用该版本的代码,将会有所帮助
  • 我做到了。我对两者都有完全相同的代码,除了另一个只是 int a[] 作为参数。
  • 没关系。我认为这个问题一开始就错了
【解决方案2】:

'temp' 的类型是 int。 'a[i]' 的类型是 *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++;
    }

【讨论】:

    猜你喜欢
    • 2015-10-19
    • 2013-09-14
    • 2011-07-04
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多