【发布时间】: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 好的。更正。