Passing an array of an array of char to a function

Posted by L.A. Rabida on Stack Overflow See other posts from Stack Overflow or by L.A. Rabida
Published on 2014-05-27T20:44:33Z Indexed on 2014/05/27 21:27 UTC
Read the original article Hit count: 184

Filed under:
|
|
|
|

In my program, I may need to load a large file, but not always. So I have defined:

char** largefilecontents;
string fileName="large.txt";

When I need to load the file, the program calles this function:

bool isitok=LoadLargeFile(fileName,largefilecontents);

And the function is:

bool LoadLargeFile(string &filename, char ** &lines)
{
    if (lines) delete [] lines;
    ifstream largeFile;
    #ifdef LINUX
    largeFile.open(filename.c_str());
    #endif
    #ifdef WINDOWS
    largeFile.open(filename.c_str(),ios::binary);
    #endif      
    if (!largeFile.is_open()) return false;
    lines=new char *[10000];
    if (!lines) return false;
    largeFile.clear();
    largeFile.seekg(ios::beg);
    for (int i=0; i>-1; i++)
    {
        string line="";
        getline(largeFile,line);
        if (largeFile.tellg()==-1) break; //when end of file is reached, tellg returns -1
        lines[i]=new char[line.length()];
        lines[i]=const_cast<char*>(line.c_str());
        cout << lines[i] << endl; //debug output
    }

    return true;
}

When I view the debug output of this function, "cout << lines[i] << endl;", it is fine. But when I then check this in the main program like this, it is all messed up:

for (i=0; i<10000; i++)
  cout << largefilecontents[i] << endl;

So within the function LoadLargeFile(), the results are fine, but without LoadLargeFile(), the results are all messed up. My guess is that the char ** &lines part of the function isn't right, but I do not know what this should be.

Could someone help me? Thank you in advance!

© Stack Overflow or respective owner

Related posts about c++

Related posts about arrays