【问题标题】:C Bubble troubleC 气泡问题
【发布时间】:2020-05-11 07:43:39
【问题描述】:

我在 C 中构建气泡时遇到了一些问题。我试图让它在整理之前、期间和之后吐出数组,但我遇到了问题。 值得一提的是,这将是我用 C 语言编写的第一个程序。 以下是我正在做的事情。

#include <stdio.h>
#define MAX 9
void printValues();
void sort();
void swap(int*, int*);

int values[] = {7, 3, 9, 4, 6, 1, 2, 8, 5};

int main(void){
        printf("Before: \n");
        printValues();
        sort();
        printf("After: \n");
        printValues();

        return(0);
}

void printValues(){
        int i;
        printf(" List before arranging: \n[");
        for (i = 0; i < 9; ++i){
                printf(" %d "values[i]);
        }
        printf("]\n");
}

void sort(){
        int i, j;
        for (i = 0; i < 9; i++){
                for (j = 0; j< 9-i; j++){
                        if (values[j] < values[j+1]){
                                swap((values + j), (values + j +1));
                        }
                }
        }
}


void swap(int x, int y){
        int temp = *x;
        *x = *y;
        *y = temp;
}

当然,我在此之前运行它并清除了我在 python3 中理解的一些错误。但是,现在我收到了这些。

bubble.c:29:16: error: expected ‘)’ before ‘values’
   printf(" %d "values[i]);
                ^
bubble.c: In function ‘sort’:
bubble.c:39:20: error: expected expression before ‘,’ token
     swap(values[j]*, values[j+1]*);
                    ^
bubble.c:39:34: error: expected expression before ‘)’ token
     swap(values[j]*, values[j+1]*);
                                  ^
bubble.c: At top level:
bubble.c:45:6: error: conflicting types for ‘swap’
 void swap(int x, int y){
      ^
bubble.c:11:6: note: previous declaration of ‘swap’ was here
 void swap(int*, int*);
      ^
bubble.c: In function ‘swap’:
bubble.c:46:13: error: invalid type argument of unary ‘*’ (have ‘int’)
  int temp = *x;
             ^
bubble.c:47:2: error: invalid type argument of unary ‘*’ (have ‘int’)
  *x = *y;
  ^
bubble.c:47:7: error: invalid type argument of unary ‘*’ (have ‘int’)
  *x = *y;
       ^
bubble.c:48:2: error: invalid type argument of unary ‘*’ (have ‘int’)
  *y = temp;
  ^

我正在尝试掌握指针的窍门,但找不到我留下的帮助。有什么帮助吗?

【问题讨论】:

  • 您的代码中充满了拼写错误。这就是大多数消息的内容。第一个警告是因为main 应该声明为int main(void)。请注意,每条消息都包含一个行号和列号,例如bubble.c:48:2 表示问题出在第 2 列的第 48 行。
  • 已解决。致歉。
  • 您解决了所有问题,还是仅解决了编辑中更改的问题?
  • 编辑。我尝试查找与交换相关的问题,但在过去几个小时内收效甚微。更改了帖子以反映更改。
  • 最好重新编译并发布更新的错误消息。这是 C 语言的标准工作流程。修复一些错误,然后重新编译,看看还有哪些错误。

标签: c arrays sorting pointers bubble-sort


【解决方案1】:

我认为您将数组和指针混合在一起是因为您编写了 values[j]* 而不是 (values + j) 并且您传递的是整数而不是 inn 指针

【讨论】:

  • 我将如何重写它?
猜你喜欢
  • 2016-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多