c++ - Program crashing when accessing 2D struct -
so have spent countless hours trying find answer question. have found close not guess post here.
i'm trying create 2d array of structs. call function create struct , input values struct. example of possible output:
input: int 5, int 5
1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25
i able create struct program keeps crashing when try input values. inputs great! here's code below.
struct values{ int mult; float div; }; values** create_table(int row, int col){ values** tab = new values*[row]; values* one_row = new values[col]; (int = 0; < row; i++){ tab[i] = one_row; } return tab; } void set_m_values(values** tab, int row, int col){ (int = 0; < row; i++){ (int j = 0; < col; j++){ tab[i][j].mult = (i+1)*(j+1); } } } int main() { int row = 5; int col = 5; values** tab = create_table(row, col); set_m_values(tab, row, col); (int = 0; < row; i++){ (int j = 0; j< col; j++){ cout <<tab[0][i].mult; } cout <<endl; } return 0; }
your initialization wrong
values* one_row = new values[col]; (int = 0; < row; i++){ tab[i] = one_row;
this creating 1 row, , assigning every row.
you meant do:
values** tab = new values*[row]; (int = 0; < row; i++) { tab[i] = new values[col]; }
that being said should using either std::array
or std::vector
.
also, , what's causing crash, in set_m_values
, have incorrect comparison:
for (int j = 0; < col; j++){ // notice in there
should be:
for (int j = 0; j < col; j++){ // replaced j
most copy pasted , forgot change it. stress fact really should using standard library containers vector this. example have:
// don't need create_table function std::vector< std::vector<values> > table(row, std::vector<values>(col));
p.s: have memory leak in code because deletes not called. not problem have std::vector
Comments
Post a Comment