简体   繁体   English

将字符串从2D指针数组分配给1D指针数组

[英]Assigning a string from a 2-D pointer array to a 1-D Pointer Array

For now, I need to do this using only arrays and pointers (so no structs or data structures) 现在,我只需要使用数组和指针(因此不需要结构或数据结构)即可

I'm trying to append an existing table of data represented as an array. 我正在尝试附加表示为数组的现有数据表。 The way I do it is by getting the data from the file and placing it all into a pointer array which I convert via a function into a 2d array whenever I want to display it. 我这样做的方法是从文件中获取数据,并将其全部放入一个指针数组,无论何时我想显示它,我都会通过函数将其转换为2d数组。

My problem is now that I'm appending data, my program crashes when it goes to the part of the code where I assign more data into my Pointer array 我的问题是现在我要追加数据,当我进入将代码分配给Pointer数组的代码部分时,程序崩溃

void appendCurTable(int oldSize, int newSize, string **ptTempData)
{
    int oldRow, newRow;
    string curFileName = "records/current.dat";
    oldRow = (oldSize/col);
    newRow = (newSize/col);
    i=0;
    int a = i+oldSize;
    readCurFile(curFileName, newSize);
    for(ir=oldRow;ir<newRow;ir++)
    {
        for(ic=0;ic<col;ic++)
        {
            *(tablePtr + a) = ptTempData[ir][ic];
            i++;
        }
    }
} 
//How tablePtr is initialized
void readCurFile(string a, int size)

{
    i = 0;
    ifstream infile;
    infile.open(a.c_str());

    tablePtr = new string[size];
    if(tablePtr==NULL)
    {
        cout<<"Insufficient Memory Allocation.\n Program will terminate.";
        exit(1);
    }

    if(infile.is_open())
    {
        while(infile.good())
        {
            getline(infile, *(tablePtr +i), ';');
            i++;
        }
        infile.close();
    }
    else
    {
        cout<<"Error opening file.";
    }

}

readCurFile creates the new Pointer array that would contain the original data and the appended data. readCurFile创建一个新的Pointer数组,其中将包含原始数据和附加数据。

Forgive the messiness, I've been tinkering here and there to see if the changes I make would fix it. 原谅混乱,我一直在这里和那里进行修补,看看我所做的更改是否可以解决它。 After all those tinkering I found that the portion within the for loop is causing the crash. 经过所有这些修改后,我发现for循环中的该部分导致崩溃。

Is there a way to make this work with pointer arrays or am I doomed? 有没有办法使它与指针数组一起工作,或者我注定要失败?

I found the answer. 我找到了答案。 I was using referencing ir to an incorrect number. 我正在使用ir引用不正确的数字。 ir's function was supposed to be for the i I've declared in the function Append. ir的功能应该是针对我在Append函数中声明的。

Correct code: 正确的代码:

void appendCurTable(int oldSize, int tempSize, int newSize, string **ptTempData)
{

    string curFileName = "records/current.dat";
    i=oldSize;
    readCurFile(curFileName, newSize);
    for(ir=0;ir<tempSize;ir++)
    {
        for(ic=0;ic<col;ic++)
        {
            tablePtr [i] = ptTempData[ir][ic];
            i++;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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