Pergunta

I'm trying to read names into a 2d dynamic array of 20 rows and where the length of the names is not limited. The program crashes at the the end with a "heap corruption" error due to a new length being introduced beyond the initial value of 10. However, the only issue encountered is when I run the loop to delete the aforementioned cells. Does anyone know how to delete cells of a different length than the initial value? (specifically in this case.) Do I need to make all cells in the array the new length? P.S. I cannot use vectors because this is a homework assignment which prohibits them.

Ok. This is the updated version with @RetiredNinja 's suggested changes. It runs just fine and I no longer have the "heap corruption" error under any of my previously tested conditions.

#include <iostream>

using namespace std;

#include <memory.h>
#include <string.h>                             // will be used once I write the sort and search functions

char * ReadString();

void main ()
{
bool contMain=true;
const long numNames=20;
long nameAc=0;
char ** ppNames, c;
ppNames=new char* [numNames];
char test;

while(contMain && nameAc<numNames)
{
    ppNames[nameAc]=ReadString();
    test=ppNames[nameAc][0];
    if(test=='\0')
    {
        contMain=false;
        break;
    }
    else;
    nameAc++;
}
for(int i=0; i<nameAc; i++)
    cout<<ppNames[i]<<endl;

// deallocation
for(int i=0; i<nameAc; i++)
{
    cout<<i<<endl;
    delete ppNames [i];
}
delete[] ppNames;
}


char * ReadString()
{
long aSize=10;
long numChars (0);
char * pNames;
char * pTemp;
char c;
pNames=new char [aSize+1];

while((c = cin.get()) != '\n')
    {
        if(numChars >= aSize)
        {
            aSize *= 2;
            pTemp = new char[aSize + 1];
            memcpy(pTemp, pNames, numChars);
            delete[] pNames;
            pNames = pTemp;
            cout << "Array size increased to " << aSize << endl;
        }
        pNames[numChars++] = c;
    }
    pNames[numChars] = '\0'; //end of string
    return pNames;
}
Foi útil?

Solução

Much of your code doesn't make much sense. You allocate and delete rather haphazardly often undoing what you did just a few lines earlier.

Try something like this instead:

char * ReadString()
{
    long aSize = 10;
    long numChars = 0;
    char * pNames;
    char * pTemp;
    char c;
    pNames = new char[aSize + 1];

    while((c = cin.get()) != '\n')
    {
        if(numChars >= aSize)
        {
            aSize *= 2;
            pTemp = new char[aSize + 1];
            memcpy(pTemp, pNames, numChars);
            delete[] pNames;
            pNames = pTemp;
            cout << "Array size increased to " << aSize << endl;
        }
        pNames[numChars++] = c;
    }
    pNames[numChars] = '\0';//end of string
    return pNames;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top