Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to copy lines from text file to array of strings (char**)

This is my code for allocating memory for the array of strings:

FileReader::FileReader()
{
    readBuffer = (char**)malloc(100 * sizeof(char*));

    for (int i = 0; i < 100; i++)
    {
        readBuffer[i] = (char*)malloc(200 * sizeof(char));
    }
}

Im alocating 100 strings for 100 lines then allocating 200 chars for each string.

This is my code for reading the lines:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

char** FileReader::ReadFile(const char* filename)
{
    int i = 0;

    File.open(filename);

    if (File.is_open())
    {
        while (getline(File, tmpString))
        {
            readBuffer[i] = (char*)tmpString.c_str();
            i++;
        }
        return readBuffer;
    }
    
}

and for printing:

for (int i = 0; i <= 5; i++)
    {
        cout << fileCpy[i];
    }

this is the output to terminal:
Picture

As you can see it just repeats the last line of the file as the file just reads:
This is test
line 2
line 3
line 4
line 5

Any idea on whats going on? Why the lines aren’t copying correctly?

>Solution :

Replace

readBuffer[i] = (char*)tmpString.c_str();

with

strcpy(readBuffer[i], tmpString.c_str());

Your version just saves a pointers to tmpString in your array. When tmpString changes then that pointer points at the new contents of tmpString (at that’s just the best possible outcome). However strcpy actually copies the characters of the string, which is what you want.

Of course, I’m sure it doesn’t need saying, but you can avoid all the headache and complication like this

vector<string> readBuffer;

This way there are no more pointer problems, no more manual allocation or freeing of memory, no limits, you aren’t limited to 100 lines or 200 characters per line. I’m sure you have a reason for doing things the hard way. but I wonder if it’s a good reason.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading