So for my homework I have to create a function for adding two matrices, the numbers are given by the user, and I think I have the function somewhat down, I just have no idea what to return because I know you can't return an array, so I tried making a variable to set it equal to but it's not working? Can someone help me out with this?
This is the part I'm stuck on:
int add_matrix(int a[][10], int b[][10], int c[][10], int Anum_rows, int Anum_cols)
{
int matrix_total = c[0][0];
for (int i = 0; i < Anum_rows; ++i) {
for (int j = 0; j < Anum_cols; ++j) {
c[i][j] = a[i][j] + b[i][j];
}
c[i][j] = matrix_total;
}
return matrix_total;
}
The last j
in the c
array is underlined with red also in visual studio.
Your code already does what it needs, it stores the resulting matrix in c
, which, since arrays are passed as pointers, will still contain the updated values when add_matrix()
returns. You just have extra code in the function, which should really not be needed to complete the matrix add operation:
void add_matrix(int a[][10], int b[][10], int c[][10], int Anum_rows, int Anum_cols) {
for (int i = 0; i < Anum_rows; ++i) {
for (int j = 0; j < Anum_cols; ++j) {
c[i][j] = a[i][j] + b[i][j];
}
}
}
Good point about Anum_cols
. There is no need to pass in the number of columns when it is specified in the argument definition and it could lead to future errors.
#define NUM_COLS 10
void add_matrix(int a[][NUM_COLS], int b[][NUM_COLS], int c[][NUM_COLS], int Anum_rows)
{
for (int i = 0; i < Anum_rows; ++i) {
for (int j = 0; j < NUM_COLS; ++j) {
c[i][j] = a[i][j] + b[i][j];
}
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments