c - 尝试使用指针在冒泡排序上编写程序时出现编译错误

标签 c sorting pointers

我尝试用 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;
}

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

enter image description here

错误信息显示:

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

任何人都可以告诉我应该如何更正我的程序以便编译并给出正确的输出吗?

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

#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;
}

最佳答案

从简短的观察中发现了两个错误:

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] 只是一个整数,您需要获取放置 & 的元素的地址,因为交换声明需要指针。

关于c - 尝试使用指针在冒泡排序上编写程序时出现编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44462448/

相关文章:

c - 使用 fork() 进行拆分过程-程序有什么问题

c - 在 C 程序中使用 chmod

mysql 根据第一个字母进行搜索

google-app-engine - 使用反射将数据从序列化动态转换回 Go 结构

c - 在 C 结构数组中,结构初始化为什么?

c - zend 自定义模块

c# - Nest/ElasticSearch按_uid排序

java - 排序 HashMap 及其嵌套的 HashMap

objective-c - 为什么 Objective-C 中的字符串指针接受并返回字符串的值而不是内存地址?

c - 函数调用期间不兼容的指针类型