【发布时间】:2014-11-05 19:18:41
【问题描述】:
#include <iostream>
#include <math.h>
#include <stdio.h>
#define column 3
#define row 3
#define share 3
int matrix_multiplication(int left_matrix[][column], int right_matrix[][column], int result_matrix[][column], int rows, int cols, int shared);
int A[][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
},
B[][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
}, C[3][3]; //initialize "hard coded" three matrices
int main() {
matrix_multiplication(A, B, C, row, column, share); //passes address of each matrix to function
return 0;
}
int matrix_multiplication(int left_matrix[][column], int right_matrix[][column], int result_matrix[][column], int rows, int cols, int shared) {
int i, j, k;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {//stays within first column and row through first iteration
for (k = 0; k < 3; k++)//ensures inner dimensions match with variable k i.e. ixk * kxj =ixj or A*B=C
result_matrix[i][j] += right_matrix[i][k] * left_matrix[k][j]; //C programming has ability to perform matrix multiplication
//Adds result of each operation to C matrix i.e. +=
printf("%d\t", result_matrix[i][j]); //matrix C is composed of rows(i) and columns(j)
}//new tab after each column iteration
printf("\n"); //new line for each row iteration
}
return 0;
}
此代码是使用指针将多维数组传递给函数并在乘法运算后打印多维数组的一个很好的示例。有多种方法可以指示指向编译器的指针。我建议查看“将二维数组传递给函数的正确方法”。例如:
/*void display(int (*p)[numcols],int numRows,int numCols)//First method//
void dispaly(int *p,int numRows,int numCols) //Second Method//
void dispaly (int p[][numCols],int numRows,int numCols) //Third Method*/
【问题讨论】:
-
二维数组是
int**,而不是int*。你在乘法线上遇到了什么错误? -
@JasonBaker 不,
int **不是 2d 数组,它是指针数组。 -
您不能将二维数组作为 c 或 c++ 中的参数作为简单的
int arr[][]参数传递。 -
请发布完整的原始错误消息,包括文件名和行号。