c++ - "unable to read memory" when filling 2D dynamic array -


the code below fails @ loop fills dynamic 2d array when trying fill first element of array. debugger tells me unable read memory. during run, rows = 7 , cols = 20, if matters.

i appreciate help. searched forum. thank you!!

// sets rows number of newline characters in file  int rows = countrows("bookmaze.txt") + 1;  /* +1 bc last row has no                                                                    newline char */  // sets number of columns number of characters on single row in file int cols = countcols("bookmaze.txt");  char **p_rows;  // allocate p_rows = new char*[rows]; (int = 0; < rows; i++)     p_rows[rows] = new char[cols];  // fill (int = 0; < rows; i++) {     (int j = 0; j < cols; j++) {         p_rows[i][j] = '*';     } } 

you have typo/bug here:

for (int = 0; < rows; i++)     p_rows[rows] = new char[cols];            ^^^^ 

it should be:

for (int = 0; < rows; i++)     p_rows[i] = new char[cols];            ^ 

note should try , away old skool c-style memory allocations , use proper c++ containers. in particular case std::vector have been better choice raw c-style arrays.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -