c++ - Printing an array of structs of structs results in an unexpected execution error? -
for struct definitions, initialize of them print contents printstruct(); after printing first element program hangs unexpectedly,
1.i thinking if malloc() fails elements right?.
2.i unfortunately have work thse structs, ideas whats wrong code below?
note: char arrays have sizes equal max length of content receive plus 1 null terminating character '\0', each team has 7 players maximum, amount of teams 21000.
sorry kind of error-checking question have never worked structs in c++ in past.
typedef struct player{ char firstname[50]; char lastname[50]; }player; typedef struct team{ int id; char title[50]; char summary[100]; int numberofplayers; player *players; }team; typedef struct teamslog{ team *arr; int numberofteams; }teams; int main() { teamslog log; log.numberofteams = 21000; log.arr = (team*)malloc(log.numberofteams * sizeof(team)); (int = 0; < log.numberofteams; ++i) { (log.arr+ i)->id = 1; (log.arr + i)->numberofplayers = 7; (int l = 0; l < 10; ++l) { (log.arr + i)->summary[l] = '0' + l; (log.arr + i)->title[l] = '0' + l; } (log.arr + i)->summary[10] = '\0'; (log.arr + i)->title[10] = '\0'; log.arr->players = (player*)malloc(7 * sizeof(player*)); (int l = 0; l < 7; ++l) { (int k = 0; k < 10; ++k){ (log.arr + i)->players[l].firstname[k] = '0' + k; (log.arr + i)->players[l].lastname[k] = '0' + k; } (log.arr + i)->players[l].firstname[10] = '\0'; (log.arr + i)->players[l].lastname[10] = '\0'; } printstruct(log.arr + i); } }
code of printstruct():
void printstruct(team* arg) { cout << "\nteam name: " << arg->title << "\nid: " << arg->id << "\nsummary: " << arg->summary << "\nnumber of players: " << arg->numberofplayers << endl; (int j = 0; j < arg->numberofplayers; ++j) cout << "player " << j+1 << " " << ((arg->players) + j)->firstname << " " << ((arg->players) + j)->lastname << endl; }
when copy/pasted code got segfault because of following:
log.arr->players = (player*)malloc(7 * sizeof(player*));
you forgot add index trying malloc memory in same spot every time go through loop, causing segfault. mentioned in comments, should using sizeof(player) instead of sizeof(player*).
following style, should be:
(log.arr + i)->players = (player*)malloc(7 * sizeof(player));
i suggest making team *arr std::vector , player *players std::vector (assuming want dynamic container). vector take care of memory management (through allocator) , improve code's readability , make easier use in future (code reuse).
Comments
Post a Comment