从c ++函数返回指针

时间:2013-10-28 08:50:58

标签: c++ function pointers return-value

我试图在以下函数中返回一个浮点数组:

static GLfloat *LoadFile(const char *filePath) {
std::ifstream f;
f.open(filePath, std::ios::in | std::ios::binary);
if(!f.is_open()){
    throw std::runtime_error(std::string("Failed to open file: ") + filePath);
}

std::stringstream buffer;
buffer << f.rdbuf();

std::string s = buffer.str();
std::string delimiter = ",";

size_t pos = 0;
std::string token;

pos = s.find(delimiter);
token = s.substr(0, pos);
int numberOfItems = ::atof(token.c_str());
s.erase(0, pos + delimiter.length());

pos = s.find(delimiter);
token = s.substr(0, pos);
int componentsPerItem = ::atof(token.c_str());
s.erase(0, pos + delimiter.length());

int dataLength = numberOfItems * componentsPerItem;

GLfloat *data = new GLfloat[dataLength + 2];
data[0] = numberOfItems;
data[1] = componentsPerItem;

int counter = 2;
while ((pos = s.find(delimiter)) != std::string::npos) {
    token = s.substr(0, pos);
    GLfloat num = ::atof(token.c_str());
    if (counter > dataLength + 1)
        throw std::runtime_error(std::string("Error in vertex data file: ") + filePath);
    data[counter] = num;
    s.erase(0, pos + delimiter.length());
    counter++;
}
return data;

}

但是当我设置一个等于返回值的变量时:

GLfloat *data = LoadData();

数据等于NULL。我的印象是因为我使用了new运算符,即使在我离开函数范围之后,该值也会保留。我做错了什么?

0 个答案:

没有答案