Unhandled exception when i try to write to 2d array - c++

So for some reason I keep getting a 'unhandled exception, would you like to break the code?' whenever i run this, like it thinks I'm going outside the array. Here's the whole code, and ill post the bit that it breaks at below:
Header file:
struct mult_div_values
{
int mult;
float div;
};
void create_table(mult_div_values ** table, int rows, int columns)
{
table = new mult_div_values * [rows];
for (int i = 0; i < columns; i++)
{
table[i] = new mult_div_values [columns];
}
}
void set_mult_values(mult_div_values ** table, int rows, int columns)
{
mult_div_values TableValues;
TableValues.div = 0;
for (int i = 0; i < rows; i++)
{
TableValues.mult = i+1;
table[0][i] = TableValues;
}
for (int i = 1; i < rows; i++)
for (int x = 0; x < columns; x++)
{
if (x == 0)
{
TableValues.mult = i + 1;
table[i][x] = TableValues;
}
else
{
TableValues.mult = (i+1) * (x + 1);
table[i][x] = TableValues;
}
}
};
void set_div_values(mult_div_values ** table, int rows, int columns)
{
mult_div_values TableValues;
for (float i = 0; i < rows; i++)
{
TableValues.div = i+1;
table[0][static_cast<int>(i)] = TableValues;
}
for (float i = 1; i < rows; i++)
for (float x = 0; x < columns; x++)
{
if (x == 0)
{
TableValues.div = i + 1;
table[static_cast<int>(i)][static_cast<int>(x)] = TableValues;
}
else
{
TableValues.div = (i+1) / (x + 1);
table[static_cast<int>(i)][static_cast<int>(x)] = TableValues;
}
}
};
Source file:
#include <iostream>
#include "mult_div.h"
using namespace::std;
struct mult_div_values;
int main()
{
mult_div_values ** table = 0;
int rows, columns, rowswanted, columnswanted;
cout << "How many rows?\n";
cin >> rows;
cout << "How many columns?\n";
cin >> columns;
cout << "Which row do you want?\n";
cin >> rowswanted;
cout << "Which column?\n";
cin >> columnswanted;
create_table(table, rows, columns);
set_mult_values(table, rows, columns);
set_mult_values(table, rows, columns);
cout << "Mult value: " << table[rowswanted][columnswanted].mult << endl << "Div value: " << table[rowswanted][columnswanted].div;
system("Pause");
}
And it breaks at:
void set_mult_values(mult_div_values ** table, int rows, int columns)
{
mult_div_values TableValues;
TableValues.div = 0;
for (int i = 0; i < rows; i++)
{
TableValues.mult = i+1;
table[0][i] = TableValues; }
as soon as i hit that last line, it gives me a error message. Any ideas?

You are iterating incorrectly in the function that creates your array:
void create_table(mult_div_values ** table, int rows, int columns)
{
table = new mult_div_values * [rows];
for (int i = 0; i < columns; i++)
// ^^^^^^^
{
table[i] = new mult_div_values [columns];
}
}
The loop should be over rows, not columns.
Also, in set:
void set_mult_values(mult_div_values ** table, int rows, int columns)
{
mult_div_values TableValues;
TableValues.div = 0;
for (int i = 0; i < rows; i++)
{
TableValues.mult = i+1;
table[0][i] = TableValues;
// ^^^
}
..
}
The i there corresponds to a column index, but you're iterating up to rows. So either that should be table[i][0] = TableValues or the loop should iterate over columns

There are likely more problems than just this, but the immediate issue is that in your create_table() method, you're passing the array pointer by value. As a result, the pointer to the 2d array that the client passes to create_table() remains NULL, and causes the crash when set_mult_values() is called.
If I may editorialize briefly, I would highly recommend simply stepping through this kind of code using a debugger before asking the question. Doing so, you would have seen the obvious NULL pointer being passed to set_mult_values().
Secondarily, consider using STL types instead of raw arrays for this kind of thing. It will make your life approximately nine-hundred times easier.

Related

Problem in rearranging rows and columns of an array

In general, given the task:
A permissible matrix transformation is a permutation of two adjacent rows or two neighboring columns. A real square matrix of order n (n <= 12) is given. Using valid converters, you can get a matrix in which the maximum element is in the upper left corner. Elements were used to perform valid conversions.
My problem is precisely that I cannot swap adjacent rows or columns.
Here is my code:
#include <iostream>
#include <algorithm>
using namespace std;
const int rows = 4, cols = rows;
int iMax = 0;
int jMax = 0;
int arr[rows][cols];
void arr_f()
{
setlocale(LC_ALL, "rus");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cin >> arr[i][j];
}
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << " " << arr[i][j] << "\t";
if (arr[i][j] > arr[iMax][jMax])
{
iMax = i;
jMax = j;
}
}
cout << endl;
}
cout << endl << "The maximum number of array: " << arr[iMax][jMax] << endl << endl;
}
int main()
{
arr_f();
system("pause");
}
Tried to add features
inline void swap_columns(const int f, const int s)
{
for (int i = 0; i < rows; ++i)
{
swap(arr[i][f], arr[i][s]);
}
}
inline void swap_rows(const int f, const int s)
{
for (int i = 0; i < rows; ++i)
{
swap(arr[f][i], arr[s][i]);
}
}
and add the following to the arr_f () function:
swap_rows(0, iMax);
swap_columns(0, jMax);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << " " << arr[i][j] << "\t";
}
cout << endl;
}
But in this case, the rows (and columns) do not change as expected (the row in which the maximum value is located is immediately replaced by the first row, ignoring the rest).
You obtained a wrong result, because swap_columns and swap_rows make operations that are not allowed. You need to make them this way:
inline void swap_columns(const int k)
{
for (int i = 0; i < rows; ++i)
{
swap(arr[i][k], arr[i][k+1]);
}
}
inline void swap_rows(const int k)
{
for (int i = 0; i < rows; ++i)
{
swap(arr[k][i], arr[k+1][i]);
}
}
And apply this way:
for (int k = iMax-1; k >= 0; --k)
swap_rows(k);
for (int k = jMax-1; k >= 0; --k)
swap_columns(k);
Certainly, this may be improved by moving larger blocks, but this is a matter of optimization.
To swap adjacent rows and columns, just replace this:
swap_rows(0, iMax);
swap_columns(0, jMax);
with this:
swap_rows(iMax + 1, iMax);
swap_columns(jMax + 1, jMax);
However, it is not clear from the problem description, whether this would always be the desired solution. And if iMax happens to be the last row index, then iMax + 1 would be out of bounds and fail at run time. In that case, perhaps iMax - 1 would be required instead.

stack around a variabe corrupted plus programs stops after inputting certain value c++

My program is meant to generate a dynamic 2d array then sort then transpose the array(swtitching columns and rows) My problem is when i input a certain value(7) for the rows and columns a stack around the variable indices becomes corrupted furthermore my code starts generating numbers that make no since i think its because it some is out of bounds please help me im relalitvely new to c++
//
// C++ program template
//
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
void init_array(int ** array_in, int rows, int cols, int list[]);
void print_array(int ** array_in, int rows, int cols);
void selection_sort(int array_in[], int elements);
int ** transpose(int ** array_in, int ** array_out, int rows, int cols);
const unsigned int SIZE = 4000;
int count1 = 0;
int main(void)
{
int rows = 0, cols = 0, j = 0, k = 0;
int**numbers = nullptr;
int**arraytranspose = nullptr;
cout << "Enter rows and columns" << endl;
cin >> rows >> cols;
int length = rows * cols;
int list[4000] = { 0 };
numbers = new int*[rows];
arraytranspose = new int*[rows];
for (k = 0; k < cols; k++)
{
numbers[k] = new int[cols];
arraytranspose[k] = new int[cols];
}
// initialize the array with unique values
init_array(numbers, rows, cols, list);
print_array(numbers, rows, cols);
selection_sort(list, count1);
int count3 = 0;
for (int count2 = 0; count2 < 3999; count2++) {
for (int i = 0; i < rows; i++)
{
for (int c = 0; c < cols; c++)
{
if (list[count2] != 0)
{
numbers[i][c] = list[count2];
}
count2++;
}
}
}
print_array(numbers, rows, cols);
cout << endl << endl;
print_array(transpose(numbers,arraytranspose,rows,cols), rows, cols);
system("pause");
return 0;
}
void selection_sort(int array_in[], int elements)
{
int index = 0, smallest = 0, hold = 0, count = 0, location = 0;
for (index = 0; index < SIZE - 1; index++) // Loop to control number of passes
{
smallest = index;
// Find the index of the smallest element
for (location = index + 1; location < SIZE; location++)
{
if (array_in[location] < array_in[smallest])
{
smallest = location;
} // End If
} // End Inner for loop
hold = array_in[smallest];
array_in[smallest] = array_in[index];
array_in[index] = hold;
count++; // Count number of swaps
}
cout << "There were " << count << " element exchanges during the sort. " << endl << endl;
return;
}
void init_array(int ** array_in, int rows, int cols, int list[])
{
int j = 0, k = 0, value = 0;
int indices[4000] = { 0 };
count1 = 0;
while (j < rows)
{
k = 0;
while (k < cols)
{
value = rand() & 4000;
if (indices[value] != 1)
{
array_in[j][k] = value;
indices[value] = 1;
list[count1] = array_in[j][k];
k++;
count1++;
}
}// end while
j++;
}
return;
}
void print_array(int ** array_in, int rows, int cols)
{
int j = 0, k = 0;
for (j = 0; j < rows; j++) {
for (k = 0; k < cols; k++) {
cout << setw(5) << array_in[j][k];
}
cout << endl;
}
return;
}
int** transpose(int ** array_in, int ** array_out,int rows, int cols)
{
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
array_out[r][c] = array_in[c][r];
}
}
return array_out;
}
numbers = new int*[rows];
arraytranspose = new int*[rows];
This allocates memory for a pair of arrays, an array of rows values.
Immediately afterwards:
for (k = 0; k < cols; k++)
{
numbers[k] = new int[cols];
arraytranspose[k] = new int[cols];
}
And this set the first cols values in these arrays, but they are rows values in size. So, if rows is less than cols, this results in memory corruption and undefined behavior, as the shown code writes to values of the array that do not exist.
This is the first obvious flaw in the shown code that's obvious from a cursory inspection, but it's likely there are other similar flaws as well; they generally result from unsafe programming practices like the ones shown here, like manual memory allocation, and lack of bounds checking. Modern C++ code offers plenty of safe programming practices, like using std::vectors to manage dynamically-sized arrays, and iterators.
Simply fixing this specific bug will be merely a bandaid, even if it turns out to be the only bug fix. Your real, long-term fix is to rewrite this entire code, and start using modern C++ containers, containers, and algorithms, which, when used correctly, will eliminate most opportunities for this entire class of bugs.

Arbitrary matrix dimension in matrix class

The task is as follows: Describe the class "matrix of numbers" with component data: the dimensions of the matrix, a pointer to the elements. Overload operations: << (matrix output to the screen), + (addition of matrices), unary ¬– (change the sign of each element), / = (divide each element by a number). I performed it, and performed it correctly, but you need to set the matrix dimension from the keyboard, and as you can see, it is set in advance for me [3] [3]. It sounds pretty simple, but something I'm really dumb. Thanks in advance for your help. Here is the code:
#include "pch.h"
#include <iostream>
using namespace std;
class Matrix
{
public:
Matrix()
{
int Table[3][3];
}
int Table[3][3];
void Create()
{
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
Table[i][j] = 10;
}
};
ostream& operator <<(ostream& t, Matrix a)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
t << a.Table[i][j] << " ";
t << "\n";
}
return t;
}
Matrix& operator /=(Matrix& a, int num)
{
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
a.Table[i][j] /= num;
return a;
}
Matrix& operator -(Matrix& a, int empty)
{
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
a.Table[i][j] = -a.Table[i][j];
return a;
}
Matrix& operator +(Matrix& a, Matrix b)
{
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
a.Table[i][j] += b.Table[i][j];
return a;
}
int main()
{
int u;
setlocale(LC_ALL, "Russian");
Matrix Example;
Example.Create();
Matrix Example1;
Example1.Create();
cout << Example;
cout << Example1;
cout << "Сумма матриц: "<<endl;
cout << Example + Example1;
Example - 1;
Example1 - 1;
cout<< Example + Example1;
cout << "На сколько вы хотите её поделить?\n";
cin >> u;
Example /= u;
Example1 /= u;
cout << Example;
cout << Example1;
}`
You need to dynamically create the matrix.
In order to this you need to use pointers(*). Change int table[3][3]
double table**;
An example of how it could be implemented (note that I use matrix instead of table)
class Matrix {
private:
double** matrix;
int col;
int row;
public:
Matrix(){};
void Create(int row, int col);
};
void Matrix::Create(int row_, int col_){
double val = 0.0;
col = col_; // initalize private members
row = row_;
matrix = new double*[row]; // Create a new array of size row_
for(int i = 0; i < row; i++)
{
matrix[i] = new double[col]; // Create new cols of size col (inside array of row)
}
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
matrix[i][j] = val;
val = val + 1.0;
}
}
}
I tried to reuse your design for simplicity, but I really suggest that you try to specify the dimensions of the matrix in a constructor instead and maybe even construct the matrix in it as well.
Something like this:
Matrix(int row_, int col_) : row(row_), col(col_) {*/ create matrix here /*};
You can skip the "create matrix here" part and use your own Create() if you want to.
You need dynamic memory allocation for that. I won't fiddle around with pointers (new / delete) unless you are explicitly told to. As a beginner you should probably use the standard template library (STL) tools:
#include <vector> and use std::vector<std::vector<int>> Table instead of int Table[3][3]. Then write a constructor like this:
Matrix(std::size_t rows, std::size_t cols)
{
Table.resize(rows);
for (unsigned int i = 0; i < Table.size(); ++i)
Table[i].resize(cols);
}
You can additionally store the dimension of the matrix, but there is no need to do it since you can get the information from the vectors. Replace the hardcoded dimensions in all loops by the corresponding dynamic sizes (stored or extracted from the vectors). For example:
Matrix& operator +(Matrix& a, Matrix b)
{
unsigned int rows = a.Table.size();
unsigned int cols = a.Table[0].size();
for (unsigned int i = 0; i < rows; i++)
for (unsigned int j = 0; j < cols; j++)
a.Table[i][j] += b.Table[i][j];
return a;
}
However, this vector of vectors is not really effective. Better would be a single vector but I guess for a beginner it is okay.
Greetings

C++ replacing matrix values with sub-matrix values

I have a University assignment whereby I have a 1D array, containing 262144 values. I've created a matrix class which places these values into an object with the datasource being the double* list of 262144 values.
I need to be able to obtain a sub-matrix (which I'm able to do) from ANOTHER set of 262144 values (which I've also placed into a matrix object).
However, I'm having serious trouble and I've been trying so hard for the last 3 days to try and replace original matrix values from a sub-matrix. I've tried passing by reference, creating Matrix*'s. I've tried everything we've been taught and even researched a few more methods, all of which I haven't understood. I'll throw my code in here to see if anyone can explain a method to me which will be able to do this.
Matrix::Matrix()
{
"Matrix::Matrix() is invoked";
}
Matrix::Matrix(const Matrix& m)
{
"Matrix::Matrix(const Matrix&) is invoked";
_M = m._M;
_N = m._N;
_data = new double[_M*_N];
for (int i = 0; i < _M*_N; i++)
{
_data[i] = m._data[i];
}
}
Matrix::Matrix(int sizeR, int sizeC, double *input_data)
{
"Matrix::Matrix(int sizeR, int sizeC, double *input_data is invoked";
_M = sizeR;
_N = sizeC;
_data = new double[_M*_N];
for (int i = 0; i < _M*_N; i++)
{
_data[i] = input_data[i];
}
}
Matrix Matrix::get_Block(int start_row, int end_row, int start_coloumn, int end_coloumn)
{
int rows = (end_row - start_row);
int columns = (end_coloumn - start_coloumn);
int ctr = 0;
double *temp_Data = new double[rows*columns];
for (int x = start_row; x < (rows + start_row); x++)
{
for (int y = start_coloumn; y < (columns + start_coloumn); y++)
{
temp_Data[ctr] = get(x, y);
ctr++;
}
}
Matrix block(rows, columns, temp_Data);
delete[] temp_Data;
return block;
}
Matrix Matrix::operator+(const Matrix & other)
{
Matrix temp;
temp._M = other._M;
temp._N = other._N;
temp._data = new double[temp._M*temp._N];
for (int x = 0; x < (temp._M*temp._N); x++)
{
temp._data[x] = this->_data[x] + other._data[x];
}
return temp;
}
Matrix Matrix::operator*(const Matrix & other)
{
Matrix temp;
temp._M = other._M;
temp._N = other._N;
temp._data = new double[temp._M*temp._N];
for (int x = 0; x < (temp._M*temp._N); x++)
{
temp._data[x] = this->_data[x] * other._data[x];
}
return temp;
}
Matrix Matrix::operator-(const Matrix & other)
{
Matrix temp;
temp._M = other._M;
temp._N = other._N;
temp._data = new double[temp._M*temp._N];
for (int x = 0; x < (temp._M*temp._N); x++)
{
temp._data[x] = this->_data[x] - other._data[x];
}
return temp;
}
void Matrix::replace_Block(Matrix& noisy, Matrix& shuffled,int k, int j, int i)
{
int val_to_replace = 0;
for (int i = 0; i < 3 * 3; i++)
{
val_to_replace = shuffled.get(i, j);
noisy.set(i, j, val_to_replace);
}
}
void Matrix::set_Block(Matrix block, Matrix& Noisy, int start_row, int end_row)
{
int ctr = 0;
int ctr2 = 0;
int ctr3 = 0;
for (int i = 0; i < 3; i++)
{
Noisy._data[(start_row*_M)+i+4] = block.get(i, ctr);
ctr++;
}
for (int j = 0; j < 3; j++)
{
Noisy._data[((start_row + 1)*_M) + j + 3] = block.get(j, ctr2);
ctr2++;
}
for (int j = 0; j < 3; j++)
{
Noisy._data[((start_row + 1)*_M) + j + 2] = block.get(j, ctr3);
ctr3++;
}
}
double Matrix::get_Sum(Matrix m)
{
double total = 0;
short row = m.get_M();
short column = m.get_N();
for (int j = 0; j < row; j++)
{
for (int i = 0; i < column; i++)
{
total += m.get(j,i);
}
}
return total;
}
double Matrix::get_Sum(Matrix* m)
{
double total = 0;
short row = m->get_M();
short column = m->get_N();
for (int j = 0; j < row; j++)
{
for (int i = 0; i < column; i++)
{
total += m->get(i, j);
}
}
return total;
}
double Matrix::get(int i, int j)
{
return _data[(i * _M) + j];
}
void Matrix::write_Block(int i, int j)
{
for (int ctr = 0; ctr < i; ctr++)
{
for (int ctr2 = 0; ctr2 < j; ctr2++)
{
std::cout << " " << this->get(ctr,ctr2);
}
std::cout << std::endl;
}
}
void Matrix::set(int i, int j, double val)
{
this->_data[(i*_M) + j] = val;
}
void Matrix::set_N(int N)
{
_N = N;
}
void Matrix::set_M(int M)
{
_M = M;
}
int Matrix::get_N()
{
return _N;
}
int Matrix::get_M()
{
return _M;
}
Matrix::~Matrix()
{
"Matrix::~Matrix() is invoked";
delete[] _data;
}
If it would be helpful to see main() I can supply that too, however all it really contains is the creation of the matrix objects using overloaded constructors.
explanation
Answer is only 4 years late . . .
Anyway. Maybe it will help somebody else. The secret is to use a std::valarray. With that it is utmost simple to work on a matrix. And, many many functions are available.
All the functions that you want to implement are already available.
And you sub-matrix coy can be a one liner . . .
Please see example code:
#include <iostream>
#include <algorithm>
#include <numeric>
#include <valarray>
#include <iomanip>
constexpr size_t NRows = 6;
constexpr size_t NCols = 8;
constexpr size_t SubNRows = 2;
constexpr size_t SubNCols = 3;
void debugPrint(std::valarray<int> &v, size_t nrows = NRows, size_t ncols = NCols)
{
for (int r = 0; r < nrows; ++r) {
for (int c = 0; c < ncols; ++c)
std::cout << std::setw(3) << v[r*ncols+c] << ' ';
std::cout << '\n';
}
std::cout << '\n';
}
int main()
{
std::valarray<int> v1(NRows * NCols); // Define array with given size
std::iota(std::begin(v1),std::end(v1),0); // Fill the array with consecutive nunbers
debugPrint (v1); // Print the result
std::cout << "\nSum = " << v1.sum() << "\n\n"; // Print the sum of all values in matrix
std::valarray<int> v2(v1); // Create a 2nd matrix as a copy to the first
v2 += 100; // Add 100 to each value in the matrix
debugPrint(v2);
std::valarray<int> v3(NCols); // Get one column
v3 = v1[std::slice(2,NRows,NCols)];
debugPrint(v3,NRows,1);
std::valarray<int> subV2(SubNRows*SubNCols); // So, now the sub array
subV2 = v2[std::gslice(12,{SubNRows, SubNCols},{NCols,1})]; // Slice it out
debugPrint(subV2, SubNRows, SubNCols);
v1[std::gslice(25,{SubNRows, SubNCols},{NCols,1})] = subV2; // And copy to the first array
debugPrint (v1);
return 0;
}

Replacing values in a 2D array

I have to create a program that allows a user to fill in a (partial) Latin Square of order 4. You can use 0's to represent empty cells. The user will give the number to place, the row and column. The number should only be placed if it does not violate the properties of a partial Latin square and it shouldn't rewrite numbers that have already been placed.
I have an matrix that is outputting all zeroes now. So next I have to replace each of these values by what the user is inputting. The problem is I don't know how to do this.
Here is my code:
#include <iostream>
using namespace std;
const int ORDER = 4;
void fill (int m[], int order);
void outputMatrix (int m[], int order);
void replaceValue (int m[], int order, int n, int row, int column);
int main(){
int matrix[ORDER];
int row;
int column;
int n;
fill (matrix, ORDER);
outputMatrix (matrix, ORDER);
do {
cout << "Enter the number to place, the row and the column, each seperated by a space: ";
cin >> n;
cin >> row;
cin >> column;
}while (n > 0 || n <= ORDER);
if (n <= 0 || n >= ORDER){
cout << "Thank you";
cout << endl;
}
return 0;
}
void fill (int m[], int order){
for (int i = 0; i < order*order; i++){
m[i] = 0;
}
}
void outputMatrix (int m[], int order){
int c = 0;
for (int i = 0; i < order*order; i++){
c++;
cout << m[i] << ' ';
if (c == order){
cout << endl;
c = 0;
}
}
cout << endl;
}
void replaceValue (int m[], int order, int n, int row, int column){
for (int i = 0; i < order; i++){
m[order] = m[row][column];
m[row][column] = n;
}
}
How do I replace values in a Matrix in C++?
If you have a matrix, matrix[row][col] = value; would do the trick. However, I see that you allocate a single array. Make sure you look at this.
EDIT:
I looked closer at you code and you are doing some things wrong.
First:
matrix[ORDER]
will create a single array of ORDER values. If you want and ORDER by ORDER matrix try:
matrix[ORDER][ORDER]
Second:
You are calling:
void fill (int m[], int order){
for (int i = 0; i < order*order; i++){
m[i] = 0;
}
}
with an of size 4 and order == 4. This will loop outside the array and give you problems.
Try something like:
matrix[ORDER][ORDER];
for (int row = 0; row != ORDER; ++row)
{
for (int col = 0; col != ORDER; ++col)
{
matrix[row][col] = 0;
}
}
Hope this helps.
You can't really write arr[i][j] if arr is defined as arr[]. There's no information about the length of the row (how many columns there are).
You could use arrays of type arr[][4], and write your functions like so:
// The & is to pass by reference.
void print(int (&arr)[][4], int length)
{
for(int i = 0; i < length; i++) {
for(int j = 0; j < 4; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
But in my opinion for a low-order multidimensional array like this one, using a typedef for a vector of vectors is the better option:
typedef vector<vector<int> > Matrix;
void print(Matrix& arr)
{
for(int i = 0; i < arr.size(); i++) {
for(int j = 0; j < arr[i].size(); j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
In either case, writing arr[i][j] = k will behave as you expect.
The easiest way to clear/zero your matrix is that:
memset( &matrix, 0, sizeof(matrix));
;-)