Vector.push_back

I am writing an application that reads data files of this format. In the file, I dynamically created a 2D array of pointers to vector objects. Basically, it reads a file, and when it finds a given line pattern, it stops and reads

while(getline(inputFile,tempTestString)){
        // first for ACCEL
        if(string::npos != tempTestString.find(ACCEL)){
            sstream.str(tempTestString);
            sstream >> pushBack;
            cout << "position 1" << endl;
            array[tempDim1][tempDim2].vectorName->push_back(pushBack);
            cout << "position 2" << endl;
            break;
        }
}

      

now pushBack is a lot, maybe up to 20,000, but it depends on the files.

The problem with this code is that I don't get runtime errors or even exceptions, I was trying to catch them. The program just ends! Of course, I added the lines cout << "position1" << endl;

and cout << "position2" << endl;

, and the last ones are printed.

If you haven't guessed:

tempTestString

and ACCEL

- string objects

sstream

- stringstream object

array

- 2D structured array in heap

vectorName

- a pointer to a vector object, a member of the structure to which it points array

ADDITION:

So, in response to some comments, here's another piece of code where all the variables were created:

array

array = new structName* [tempDim1];
for(int i = 0; i < tempDim2; i++){
    array[i] = new structName [tempDim2];
}

      

structName

struct structName{
    vector<double>* vectorName;
    vector<double>* vectorName1;
    vector<double>* vectorName2;
 };

      

tempDim1 and tempDim2 are both const ints

, values ​​2 and 3 respectively. pushBack can be up to 20,000

+3


source to share


2 answers


Try to fix this:

array = new structName* [tempDim1];
for(int i = 0; i < tempDim2; i++){
    array[i] = new structName [tempDim2];
}

      



=>

array = new structName* [tempDim1];
for(int i = 0; i < tempDim1; i++){
    array[i] = new structName [tempDim2];
}

      

+3


source


Wrong cardinality used in initialization.

array = new structName* [tempDim1];
for(int i = 0; i < tempDim2; i++){
    array[i] = new structName [tempDim2];
}

      



i < tempDim2

wrong; the array has tempDim1 elements.

I don't know if this is a problem, but it is a problem. If tempDim1> tempDim2, then some elements of the [] array will be uninitialized. (And if it's the other way around, you're corrupting memory.) The only way this will work is if tempDim1 and tempDim2 are the same.

0


source







All Articles