Search code examples
c++pointersstructmatrixdouble-pointer

Double pointer that points on self-created struct - Compiler says OK - Programm aborts


Right now, I prepare for an exam (university) and thought of creating my own exercises. I thought of programming a pascal triangle where the places in the matrix (implemented with double pointer to the struct) are filled with Objects of the type of my struct.

Here's my code:

#include <iostream>
#include <string>
using namespace std;

int main(){
    struct Ferrari{
    string Modell;
    int Baujahr;
    int PS;
    };
Ferrari **matrix = new Ferrari* [5];
for(int i=0; i<5; i++){
    matrix[i]=new Ferrari[i+1];
}
matrix[0][0].Modell="F40";
matrix[0][0].Baujahr=2012;
matrix[0][0].PS = 210;
matrix[1][0].Modell=matrix[1][1].Modell="Enzo";
matrix[1][0].Baujahr=matrix[1][1].Baujahr=2000;
matrix[1][0].PS=matrix[1][1].PS=210;
for(int i=2; i<5; i++){
    for(int j=0; j<=i; j++){
        matrix[i][j].Modell=matrix[i-1][j].Modell + matrix[i-1][j-1].Modell;
        matrix[i][j].Baujahr=matrix[i-1][j].Baujahr + matrix[i-1][j-1].Baujahr;
        matrix[i][j].PS=matrix[i-1][j].PS + matrix[i-1][j-1].PS;
    }
}
for(int i=0; i<5; i++){
    for(int j=0; j<=i; j++){
        cout << matrix[i][j].Modell << "   ";
        cout << matrix[i][j].Baujahr << "   ";
        cout << matrix[i][j].PS << "   ";
    }
    cout << endl;
}
system("pause");
return 0;

}

The Programm does many weird things, but not what it should do. Compiler says ok, but when I run it it gives me the error code: Unhandled exception at 0x72f7ae7a in Testerei.exe: 0xC0000005: Access violation reading location 0xabababab.

At that point, somehow my variable i has the value -33651 ...

Could you maybe tell me where the problem of the code is? I know, the programm has no real function...I just wanted to practise a bit with double pointers, structs, strings (addition of strings...).

Thank you in advance!

Best regards,

Manuel


Solution

  • This a bug:

    for(int j=0; j<=i; j++){
        matrix[i][j].Modell=matrix[i-1][j].Modell + matrix[i-1][j-1].Modell;
    

    as an attempt is being made to access an array with an index of -1 when j = 0.