【问题标题】:Error in compilation while trying to write a program on bubble sort using pointers尝试使用指针在冒泡排序上编写程序时出现编译错误
【发布时间】:2017-11-11 17:54:53
【问题描述】:

我尝试用 C 语言编写一个程序来“冒泡排序”一系列数字,这些数字是使用指针作为输入获得的。如下:

#include<stdio.h>
void swap(int *p,int *q)
{
  int t;
  t=*p;
  *p=*q;
  *q=t;
}
void sort(int *a[],int n)
{
  int i,j;
  for(i=0;i<n-1;i++)
  {
    for(j=0;j<n-i-1;j++)
    {
      if(a[j]>a[j+1])
      swap(a[j],a[j+1]);
    }
  }
}      
int main()
{
  int p[40],b,i;
  printf("Enter the number of elements in the sequence: \n");
  scanf("%d",&b);
  printf("Enter the elements of the sequence: \n");
  for(i=0;i<b;i++)
  {
    scanf("%d",p[i]);
  }
  sort(p,b);
  printf("The sorted sequence is: \n");
  for(i=0;i<b;i++)
  {
    printf("%d \n",p[i]);
  }
  return 0;
}

但是,程序没有编译。它显示以下错误消息:

错误信息显示:

error 139 - Argument no 1 of 'sort' must be of type '<ptr><ptr>int', not 'int[40]'

谁能告诉我应该如何更正我的程序以便编译并给出正确的输出?

ADDENDUM:以下是更正后的代码,按要求-

#include<stdio.h>
void myswap(int *p,int *q)
{
  int t;
  t=*p;
  *p=*q;
  *q=t;
}
void sort(int a[],int n)
{
  int i,j;
  for(i=0;i<n-1;i++)
  {
    for(j=0;j<n-i-1;j++)
    {
      if(a[j]>a[j+1])
      myswap(&a[j],&a[j+1]);
    }
  }
}      
int main()
{
  int p[40],b,i;
  printf("Enter the number of elements in the sequence: \n");
  scanf("%d",&b);
  printf("Enter the elements of the sequence: \n");
  for(i=0;i<b;i++)
  {
    scanf("%d",&p[i]);
  }
  sort(p,b);
  printf("The sorted sequence is: \n");
  for(i=0;i<b;i++)
  {
    printf("%d \n",p[i]);
  }
  return 0;
}

【问题讨论】:

  • 你声明sort的第一个参数是一个指向int的指针数组,但是当你调用它时你传递了一个指向int的指针(记住数组自然衰减到指针到他们的第一个元素)。这两种类型在任何方面都不相似。
  • 将 &p[i] 传递给 scanf。
  • @JonathanLeffler 谢谢。我纠正了它。但是编译器再次显示同样的错误。
  • 您的图像在手机上无法读取——人们不喜欢在问题中嵌入图像的另一个原因。请将错误消息的文本直接嵌入问题中,作为“代码”(换句话说,缩进)。
  • @JonathanLeffler 好的。更正。

标签: c sorting pointers


【解决方案1】:

看了一眼发现了两个错误:

void sort(int *a[],int n)

应该是

void sort(int a[],int n)

swap(a[j],a[j+1])

应该是

swap(&a[j],&a[j+1])

a[j] 只是一个整数,您需要获取放置 &amp; 的元素的地址,因为交换声明需要指针。

【讨论】:

  • 谢谢!该程序现在正在运行..但是你能告诉我错误的真正含义吗?为什么上面所说的事情是错误的?
  • 错误提示“你正在传递一个int,你需要传递一个int *”。您的代码传递了int(例如a[i]),但您应该传递了int *(例如&amp;a[i])。 scanf() 问题可能没有为您确定,但实际上是同一个问题——您传递了一个 int ,而 scanf() 需要一个 int *
  • 我不知道你程序的行,但我认为第一个错误与@Jonathan Leffler 评论有关,另一个说你将 传递给 int,在声明void sort(int *a[],int n)' but you only pass a which is &lt;ptr&gt; to int. When you want to pass an array a to a function then the function declaration should be like a[]`的情况,它表示一个未知大小的数组,或者只是*a,因为在这种情况下数组就像一个指针......
  • @coder 是的,by a,我的意思是a[ ]。但是,就像你说的,当我使用sort 函数时,我尝试输入a[ ] in place of a。它仍然给出同样的错误。
  • 您能否编辑并给我们您的最终(更改)代码?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-21
  • 1970-01-01
  • 1970-01-01
  • 2012-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多