Segmentation fault, strange

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
char grid [row][col]=
    {
        {'O', 'O',' ','O', 'O', 'O'},
        {'O', ' ','X','X', 'O'},
        {' ', 'O',' ',' ', ' '},
        {'O', 'O',' ','X', 'O'},
        {'O', 'O',' ',' ', 'X'},

        {'O', ' ','O',' ', ' '},
        {' ', 'O','O',' ', 'X'},
        {'O', ' ','O','O',' '},
        {' '}
    };

    //Enter game?
    cout<<"\t\tWelcome ANT VS BUG Game"<<endl<<endl;
    initialise(grid);

    displayGrid(grid);

    cout<<"Press any key to proceed... ";
    cin>>start;


    cout<<endl;
    //initialise the objects 20 x 20 Organism Grid
   /* Organism** organisms= new Organism* [row];
    for(int i=0; i<row; i++)
    {
        organisms[i]=new Organism[col];


    }*/

    Organism *organisms[row][col];

    //Setposition for Ant and bugs here from grid


    for(int i=0; i<row; i++)
    {

        for(int j=0; j<col; j++)
        {

            if(grid[i][j]=='O')
            {

                Ant* ant=new Ant();
                organisms[i][j]=ant;
                //setposition now
                organisms[i][j]->setPositionCurrentX(i);
                organisms[i][j]->setPositionCurrentY(j);



            }
            else if(grid[i][j]=='X')
            {
                DoodleBug* bug=new DoodleBug();
                organisms[i][j]=bug;
                //setposition now
                organisms[i][j]->setPositionCurrentX(i);
                organisms[i][j]->setPositionCurrentY(j);

            }


            //indexAnt=0;
            //indexBug=1;
        }
    }

    srand(time(NULL));//for random seed
    while(quit=='N')//while not N
    {

        cout<<"Ant Turn"<<endl;
        for(int m=0; m<row; m++)//the moment I enter loop I get the error
        {
            for(int n=0; n<col; n++)
            {
                if(organisms[m][n]->isAnt()==true && organisms[m][n]->getSurvive()==true)
Last edited on
Locations in organisms where the grid value is not 'X' or 'O' are never initialized.
Last edited on
Let mee try
Last edited on
I mean the organisms 2D array. You are not assigning a value to all pointers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
for(int i=0; i<row; i++)
{
	for(int j=0; j<col; j++)
	{
		if(grid[i][j]=='O')
		{
			// Assign organisms[i][j]
		}
		else if(grid[i][j]=='X')
		{
			// Assign organisms[i][j]
		}
		else
		{
			// organisms[i][j] is left uninitialized!
		}
	}
}
Changing line 35 to

Organism *organisms[row][col] = {0}; /* C or C++ */

or

Organism *organisms[row][col] = {}; // C++

will zero all elements of the array (i.e. set them to NULL in pointer terms.)

Then you only have to worry about the "bugs" and "ants" when creating populating the object array.

Andy
Last edited on
Topic archived. No new replies allowed.