I am using C++ to break down soccer games. I have games broken down into the struct "Events," as such:
1 2 3 4 5 6 7 8 9
|
struct Event {
unsigned int scoreA; //score of teamA at any point in time
unsigned int scoreB; //score of teamB
unsigned int STime; //start/end time of the event
unsigned int ETime;
struct Game *thegame; //pointer to a game the Event is in
struct Event *nextevent; //pointer to next event in line, or null
};
|
I have a function addEvent that is supposed to add an event to a game, with an auxiliary function LastEvent that returns a pointer to the last event in the game.
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
|
typedef struct Event *Eventp;
typedef struct Game *Gamep;
void addEvent( Eventp nwevnt, Gamep g) {
if((g->ev) == NULL) {
g->ev = nwevnt;
++(g->EventNum);
}
else {
Eventp swtch = LastEvent( g->ev);
swtch->nextevent = nwevnt;
++(g->EventNum);
}
}
Eventp LastEvent ( Eventp EV) { //ev can NEVER be a null pointer, need something to account for this
if((EV->nextevent) == NULL)
return EV;
else return LastEvent (EV->nextevent);
}
|
In main, I start with a Game that has no events (instead just a pointer to NULL) then try to use addEvent to add in the first game.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
int main()
{
...
Eventp first = NULL;
Gamep PGame = MGame ( "Manu", 1, "Chelsea", 2, 2, 0, first, 0, "This is a practice Game");
...
Eventp PEvent = MEvent( 1, 0, 20, 30, PGame, NULL); //creates an Event
addEvent(PEvent, PGame); //adds Event to the Game, segfaults!!
...
return 0;
}
|
Where obviously the "..." indicates code that is unnecessary so I've blanked it out.
When I run GDB on this code, it says its segfaulting at....
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400c9c in LastEvent (EV=0x100000000) at FIFA1.cpp:45
45 if((EV->nextevent) == 0)
I understand why this is a segfault--the argument EV is a NULL pointer, so obviously EV->nextevent doesn't exist. But, if that is indeed the case, why the heck aren't any of my conditional statements working?? Why doesn't the first line of code in addEvent ( if( g->ev = NULL) ... ) work???
Well, I know why it doesn't work--when I print EV in GDB, it gives the address as 0x10000 blah blah. In other words, the address isn't NULL. WHAT? but I TOLD TOLD TOLD it to be NULL in main when I had the command
Eventp first = NULL
What the heck is going on here?? What am I missing?