I'm new to coding and am currently learning C at school. I had a question regarding how to add matrices in C using a function. I'm facing some difficulties and was hoping to get some words of advice here. The conditions that my instructor gave the class are 1) two 5 x 6 matrices with integer entries from 1 - 100, 2) define and use your own function. Here's the code I've written so far:
#include <stdio.h>
#include <stdlib.h>
#define ROW 5
#define COLUMN 6
size_t addMatrices(int a[][COLUMN], int b[][COLUMN]);
void printArray(int a[][COLUMN]);
int main(void) {
int row, column;
int matrix1[ROW][COLUMN] = { {0}, {0} };
int matrix2[ROW][COLUMN] = { {0}, {0} };
for (row = 0; row < ROW; row++) {
for (column = 0; column < COLUMN; column++) {
matrix1[row][column] = 1 + (rand() % 100);
matrix2[row][column] = 1 + (rand() % 100);
}
}
printf("matrix1:\n");
printArray(matrix1);
printf("\n\nmatrix2:\n");
printArray(matrix2);
printf("\n\nresult:\n");
addMatrices(matrix1, matrix2);
printfArray(result);
printf("\n");
return 0;
}
void printArray(int a[][COLUMN]) {
int row, column;
for (row = 0; row < ROW; row++) {
for (column = 0; column < COLUMN; column++) {
printf("%d ", a[row][column]);
}
printf("\n");
}
}
size_t addMatrices(int a[][COLUMN], int b[][COLUMN]) {
int result[ROW][COLUMN] = { {0}, {0} };
int row, column;
for (row = 0; row < ROW; row++) {
for (column = 0; column < COLUMN; column++) {
result[row][column] = a[row][column] + b[row][column];
}
}
return result;
}
If you look at the body of the main method, the compiler says that there's an error because the variable "result" isn't defined when being passed to the function printArray(). I understand the concept of why this error occurs (regarding local variables and passing parameters), but how can I solve this problem?
Aside from this, any other words of advice or suggestions are greatly appreciated.
Thank you!
int result[ROW][COLUMN] = { {0}, {0} };move tomain. and callvoid addMatrices(int a[][COLUMN], int b[][COLUMN], int result[][COLUMN]) {int result[ROW][COLUMN] = { {0}, {0} };from a function. It is created on the function stack which is destroyed on function return. Either (1) dynamically allocateresultor (2) pass it as a parameter to your add function.mainis a function in C++, too.-Wall -Wextrain your compile string) and do not accept code until it compiles cleanly without warning or error.