#include <stdio.h> //파라미터로 계산할 mat1과 mat2, 저장할 result1 사용 void sum(int* mat1, int* mat2,…
- User
#include <stdio.h>
//파라미터로 계산할 mat1과 mat2, 저장할 result1 사용 void sum(int* mat1, int* mat2, int* result, int size);
//파라미터로 계산할 mat1과 mat2, 저장할 result2 사용 void mul(int* mat1, int* mat2, int* result, int size);
int main() { int mat1[1] = {0}; int mat2[4] = {0}; int result1[4] = {0}; int result2[4] = {0}; //배열 값 입력, 함수 호출, 결과 출력
printf("Please input Array mat1's element : "); for(int i=0; i<4; i++){ scanf("%d", &*(mat1 + i)); } printf("Please input Array mat2's element : "); for(int i=0; i<4; i++){ scanf("%d", &*(mat2 + i)); } printf("\n"); sum(mat1, mat2, result1, 4); mul(mat1, mat2, result2, 4); printf("Result of sum Function\n"); printf("result1 = { "); for(int i=0; i<4; i++){ printf("%d ", *(result1 + i)); } printf("}\n\n"); printf("Result of mul function\n"); printf("result2 = { "); for(int i=0; i<4; i++){ printf("%d ", *(result2 + i)); } printf("}\n\n"); return 0;}
//result1의 element에 mat1 element와 mat2 element를 더한 결과를 저장 void sum(int* mat1, int* mat2, int* result, int size) { for(int i=0; i<size; i++){ *(result + i) = *(mat1 + i) + *(mat2 + i); } }
//result2의 element에 mat1의 element와 mat2의 element를 더한 결과를 저장 void mul(int* mat1, int* mat2, int* result, int size) { for(int i=0; i<size; i++){ *(result + i) = *(mat1 + i) * *(mat2 + i); } }
HEY! WHAT is result of this cord?
- Assistant
This C program reads two arrays (mat1 and mat2) from the user, performs element-wise addition and multiplication on the respective arrays, and stores the results in two other arrays (result1 and result2). However, there are a couple of errors and important points to address:
-
Incorrect array sizing and out of bounds access:
mat1is declared with size 1 but later accessed and used as if it had size 4. This causes undefined behavior because indexes mat1[1], mat1[2], and mat1[3] are accessed, but they don't exist.- To fix it,
mat1should be declared asint mat1[4];
-
Printing results: The results of the two operations (summation and multiplication) are printed out.
-