简体   繁体   中英

Exception Error while char input from file in 2D Pointers and Regrowing

I am trying to input names from a file to a double pointer. Since, the file structure is as such that i don't know how many names will I encounter. I am regrowing my pointer both 2D and 1D at run time. But the problem is that since i am using fin.eof() in my while loop. When all the names have been entered, the loop doesn't detect the end of file and adds another array to the 2D pointer and since it hasn't any memory allocated yet. And then it tries to add '\\0' to unallocated memory and then it throws an exception error.

#include <iostream>
#include <fstream>

using namespace std;

void OneDRegrow(char * & ptr, int & size)
{
    char * temp = new char[size];
    for (int i = 0; i < size; i++)
    {
        temp[i] = ptr[i];
    }
    if(!ptr)
        delete[] ptr;
    ptr = temp;
    size++;
}

void TwoDRegrow(char ** & ptr, int & size)
{
    char ** temp = new char*[size + 1];
    for (int i = 0; i < size; i++)
    {
        temp[i] = ptr[i];
    }
    delete[] ptr;
    ptr = temp;
    temp = nullptr;
    size++;
}

bool Read(ifstream & fin, char ** & ptr, int & rows)
{
    if (!fin.is_open())
        return false;
    rows = 0;
    int cols = 0;
    char ch = '\0';
    while (!fin.eof()) {
        TwoDRegrow(ptr, rows);
        cols = 0;
        fin >> ch;
        while (ch != ';') {
            OneDRegrow(ptr[rows-1], cols);
            ptr[rows - 1][cols-1] = ch;
            fin >> ch;
        }
        ptr[rows - 1][cols] = '\0';
    }
}

void Print2D(char ** ptr, int size)
{
    for (int i = 0; i < size; i++)
    {
        cout << ptr[i] << endl;
    }
}

int main()
{
    int size;
    char ** ptr = NULL;
    ifstream fin("input.txt", ios::in);
    Read(fin, ptr, size);
    Print2D(ptr, size);
    system("pause");
    return 0;
}

Input from my file is as follows:

Roger;
James;
Mathew;
William;
Samantha;

Do it the right way

while (fin >> ch) {
    TwoDRegrow(ptr, rows);
    cols = 0;
    while (ch != ';') {
        ...

Never (almost) use eof as the condition in a while loop, for exactly the reasons you have found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM