2014-10-04 72 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; 

}