-5

我已经使用指针为冒泡排序编写了这段代码,但是我收到了需要 LVALUE 之类的错误。

这是我的代码。请修复此代码。我基本上在交换语法时遇到错误。请帮忙

#include<stdio.h>
#include<conio.h>
void sort(int *a,int n);
void main()
{
    int a[20];
    int n,i;
    clrscr();
    printf("Program for BUBBLE SORT\n");
    printf("Enter the Number of ELements you want in Array\n");
    scanf("%d",&n);
    printf("Enter the Elements in UNSOTED ARRAY\n");
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    printf("The Unsorted ARRAY is:\n");
    for(i=0;i<n;i++)
    {
        printf("%d\t",a[i]);
    }
    printf("\n");
    sort(&a,n);
    getch();
}
void sort(int *a,int n)
{
    int i,temp,j;
    for(i=1;i<n;i++)
    {
        for(j=0;j<n-i;j++)
        {
            if((*a+j)==(*a+j+1))
            {
                temp=*a+j;
                *a+j=*a+j+1;
                *a+j+1=temp;
            }
        }
    }
}
4

2 回答 2

8

最好让你的交换部分像这样:

temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;

特别是如果您是 C 的初学者,用于简单数组访问的带有指针数学的花哨语法并不能帮助您理解自己的代码。

此外,您可能希望像这样调用排序函数:sort(a, n),因为在 C 中a已经意味着&a[0]。如果您开始抛出更多引用运算符,您最终将访问超出您预期的其他内存。

于 2013-04-28T16:14:30.337 回答
1

您只是缺少几个括号:

if(*(a+j)==*(a+j+1))
{
    temp=*(a+j);
    *(a+j)=*(a+j+1);
    *(a+j+1)=temp;
}

它们是必需的,因为您想将 j 添加到 a,然后取消引用该地址。

于 2013-04-28T16:13:14.930 回答