双维向量的运行时错误

时间:2013-07-31 04:57:37

标签: c++ vector runtime

我使用双维向量时遇到问题。我已经在我的头文件中将双向量声明为extern,并且在main()调用之前在main.cpp文件中再次声明(不是作为extern)。我调用一个函数来动态地为双向量分配内存。给定的代码不会产生编译错误。但是在运行时如果访问向量,它会给出一个超出范围异常的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";
}

1 个答案:

答案 0 :(得分:0)

您的函数调用function()对main.cpp中定义的变量buffer没有副作用。因此,在您的main函数中,它尝试访问它将导致未定义的行为。

如果您打算让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
}