簡體   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