2014-10-04 71 views
-1

我得到它的錯誤:「列表未在此範圍內定義」[主main()內] 我已經嘗試了幾件事但結束了失敗。我已經閱讀了一些示波器教程,並沒有發現任何內容:\,所以我來到這裏,希望有人可以幫忙。C++變量範圍錯誤

[CODE:]

#include <iostream> 

using namespace std; 


const int MAX_LIST_SIZE = 100; 
typedef int element; 
typedef element list_type[MAX_LIST_SIZE]; 


void bubble_sort(); 

int main() { 
    cout << list[0] << list[1] << list[2] << list[3] << list[4] << endl; 
    return 0; 
} 

void bubble_sort(list_type list, int n) { 

    list[0] = 43; 
    list[1] = 20; 
    list[2] = 24; 
    list[3] = 31; 
    list[4] = 36; 

    n = 5; 
    int j, k; 
    bool exchange_made = true; 
    element temp; 

    k = 0; 
    // make up to n- 1 passes through array, exit 
    // early if no exchange are made on previous pass 
    while((k < n -1) && exchange_made) { 
     exchange_made = false; 
     ++k; 
     // number of comparisons on kth pass 
     for (j = 0; j < n - k; ++j) 
     if(list[j] > list[j + 1]) { 
      // exchange must be made! 
      temp = list[j]; 
      list[j] = list[j + 1]; 
      list[j + 1] = temp; 
      exchange_made = true; 
     } 
    } 

}

回答

0

在代碼中,你從來沒有宣佈list你的主塊。錯誤信息清楚地告訴你這個問題。

+0

噢日Thnx .. :) – 2014-10-04 02:48:05

+0

功能有自己的局部範圍。所以main不知道'bubble_sort'函數中的'list'。 – slik 2014-10-04 02:50:45

0

您應該定義list。它沒有在任何地方定義。

int arr[MAX_LIST_SIZE]; 
1
int main() { 

    cout << list[0] << list[1] << list[2] << list[3] << list[4] << endl; 
    return 0; 
} 

list僅在功能bubble_sort定義,所以知道的方式,main可以訪問它。這是一個問題。這是讓你開始的東西。

#include <iostream> 

using namespace std; 


const int MAX_LIST_SIZE = 100; 
typedef int element; 
typedef element list_type[MAX_LIST_SIZE]; 


void bubble_sort(); 

int main() { 
    bubble_sort(); //you need to actually CALL bubble_sort for it to do anything 
    return 0; 
} 

void bubble_sort() { 
    list_type list; //no need to have the variables as a parameter 
    int n = 5;  //just declare them in the scope (inside the function) that you need them in 
    list[0] = 43; 
    list[1] = 20; 
    list[2] = 24; 
    list[3] = 31; 
    list[4] = 36; 

    int j, k; 
    bool exchange_made = true; 
    element temp; 

    k = 0; 
    // make up to n- 1 passes through array, exit 
    // early if no exchange are made on previous pass 
    while((k < n -1) && exchange_made) { 
     exchange_made = false; 
     ++k; 
     // number of comparisons on kth pass 
     for (j = 0; j < n - k; ++j) 
     if(list[j] > list[j + 1]) { 
      // exchange must be made! 
      temp = list[j]; 
      list[j] = list[j + 1]; 
      list[j + 1] = temp; 
      exchange_made = true; 
     } 
    } 

    cout << list[0] << list[1] << list[2] << list[3] << list[4] << endl; 

}