2013-07-31 62 views
1

我有一個問題,使用二維向量。我在我的main()調用之前在我的頭文件中聲明瞭雙向量,並且在main.cpp文件中再次聲明瞭雙向量(不是extern)。我調用一個函數來動態地分配內存給雙向量。給定的代碼不會給出編譯錯誤。但是在運行時,如果你訪問vector,它會給Vector下標超出範圍異常。我使用我的調試器檢查了它,發現矢量在函數中分配了內存,但一旦它返回(超出函數範圍),矢量大小就會回到0. 我已附上代碼運行時錯誤的二維向量

color.h:

#ifndef __COLOR__ 
#define __COLOR__ 

class color{ 
     public : 
     int r,g,b; 

     color(void); 
     color(int R, int G,int B); 
    }; 
#endif 

color.cpp

#include"color.h" 
#include <iostream> 

color::color(void){ 
    r=g=b=0; 
} 
color::color(int R, int G,int B){ 
    if(R<=1 && G<=1 && B<=1){ 
    r=R;g=G;b=B; 
    } 
    else{ 
    std::cout<<"Error in RGB values"; 
    } 
} 

header.h:

#ifndef __HEADER__ 
#define __HEADER__ 

    #include <iostream> 
    #include <vector> 

    #include "color.h" 

    const int windowWidth=200; 
    const int windowHeight=200; 

    void function(); 

    extern std::vector <std::vector<color> > buffer; 

#endif __HEADER__ 

color.cpp

#ifndef __COLOR__ 
#define __COLOR__ 

class color{ 
     public : 
     int r,g,b; 

     color(void); 
     color(int R, int G,int B); 
    }; 
#endif 

的main.cpp

#include "header.h" 
std::vector <std::vector<color> > buffer; 
void main(void){ 
    //myClass obj=myClass(1,4); 

    function(/*obj*/); 
    std::cout<<"HI"; 
      std::cout<<"vector : "<<buffer[0][0].r; //VECTOR SUBSCRIPT OUT OF RANGE 
    getchar(); 
} 
void function(){ 
    std::vector <std::vector<color> > buffer (2*windowHeight, std::vector<color>(2*windowWidth)); 
    std::cout<<"HI"; 
} 

回答

0

你的函數調用function()有它在main.cpp中定義的變量buffer無不良影響。所以在你的主函數中,它試圖訪問它會導致未定義的行爲。

如果您打算讓function()修改全局buffer變量,那麼可以讓function()返回該向量。

std::vector <std::vector<color> > function() 
{ 
    std::vector <std::vector<color> > buffer (2*windowHeight, std::vector<color>(2*windowWidth)); 
    std::cout<<"HI"; 
    return buffer; 
} 

int main() 
{ 
    buffer = function(); 
    std::cout<<"vector : "<<buffer[0][0].r; // now you should be fine to access buffer elements 
}