繁体   English   中英

C中的冒泡排序函数-未定义符号错误

[英]bubble sort function in C - undefined symbols error

我正在尝试编写一个简单的程序来对整数数组进行冒泡排序。 我收到错误消息:

Segmentation Fault

我知道这通常与链接正确的库有关,但是我不确定我缺少哪一个?

这是我的程序:

 //Bubble Sort program

#include <stdio.h>
#include <stdlib.h>

void bubblesort(int list[], int N);



//To do: write a function to allocate an array of size N. N will be input by the user

//TODO:Write a function allocatearray()
int *allocatearray(int N){
  int *array;                  
  array = malloc(N * sizeof(int));    //making an array of changeable size
  return array;
}

int main()  {
  int *array;
  int n, i, d, swap;

  printf("Enter number of elements\n");
  scanf("%d", &n);

  printf("Enter %d integers\n", n);

  for (i = 0; i < n; i++)
    //scanf("%d", &array[i]); 
      scanf("%d", &array[i]);  
      bubblesort(array, n);

  printf("Sorted list in ascending order:\n");
  for ( i = 0 ; i < n ; i++ ) {
     printf("%d\n", array[i]);
     }

  return 0;
}

//TODO:Write a function bubblesort()
void bubblesort(int list[], int N) {
  int i, d, t;
  for (i = 0 ; i < (N - 1); i++) {        //array of entered integers
    for (d = 0 ; d < (N - i - 1); d++) {  //d array is one smaller than c
        if (list[d] > list[d+1]) {            //if value "d" is greater than "d + 1"
        /* Bubble swap */
        t = list[d];                     //create new long variable t equal to value of list[d]
        list[d] = list[d+1];             //update d value to d + 1 value
        list[d+1] = t;                   //
        }
       }
      }
     }

谢谢您的帮助!

您可以将函数bubble_sort()实际命名为bubblesort() 您还必须在主函数之前创建一个定义,例如添加:

void bubblesort(int list[], int N)

就在int *allocatearray(int N)定义的下面。

您尝试在main函数中使用函数bubble_sortbubble_sort在任何地方声明该函数,因此编译器抱怨找不到该方法。

即使这只是一个错字错误,由于main函数位于上方的bubblesort ,因此调用bubblesortbubblesort ,因此编译器将抱怨它不知道任何名为bubblesort方法。 您需要将bubblesort方法放在main方法之前,或者在您的main方法之前添加一个原型行:

//declare the signature of the method, the implementation is found below.
void bubblesort(int list[], int N);

您试图在main中使用函数bubbleort而不在c源文件的顶部声明它。

您有两种方法可以遵循:

  1. 剪切和粘贴气泡排序功能到顶部:

     #include <stdio.h> #include <stdlib.h> //To do: write a function to allocate an array of size N. N will be input by the user //TODO:Write a function allocatearray() int *allocatearray(int N){ int *array; array = malloc(N * sizeof(int)); //making an array of changeable size return array; } void bubblesort(int list[], int N) { int i, d, t; for (i = 0 ; i < (N - 1); i++) { //AND ON... int main() { // ... } 
  2. 只需在顶部添加函数定义:

     void bubblesort(int list[], int N); 

    在#includes下方。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM