Two-dimensional array and two-dimensional pointer passing Parameters

Source: Internet
Author: User

Problem:
For a matrix A (n columns in m rows) and B (p columns in N rows), the product C (P columns in m rows) is obtained ), in this case, two-dimensional array names are used to pass real parameters, but how to pass them? Can two-dimensional pointers be used directly for parameters? (For example, int matrixmultiplication (INT ** A, int ** B, int ** C, int Ra, int ca, int RB, int CB). This is not acceptable !)
There are two feasible methods:

Method 1: The form parameter uses a pointer to a one-dimensional array, for example, INT (* P) [4 ].

#include <iostream>using namespace std;#define M 3#define N 4#define P 5int MatrixMultiplication(int (*A)[N], int (*B)[P], int (*C)[P], int ra, int ca, int rb, int cb);void main(){int A[M][N] = {{1, 2, 3, 1},{3, 1, 5, 5},{8, 1, 6, 2} };int B[N][P] = {{1, 2, 3, 1, 0},{3, 1, 5, 2, 5},{0, 1, 6, 3, 1},{1, 0, 5, 2, 2} };int C[M][P];if (MatrixMultiplication(A, B, C, M, N, N, P) == 1){for (int i = 0; i < M; i++){for (int j = 0; j < P; j++){cout << C[i][j] << " ";}cout << endl;}}else{cout << "ERROR!" << endl;}}int MatrixMultiplication(int (*A)[N], int (*B)[P], int (*C)[P], int ra, int ca, int rb, int cb){if (ca != rb)return 0;for (int i = 0; i < ra; i++){for (int j = 0; j < cb; j++){int sum = A[i][0] * B[0][j];for (int k = 1; k < ca; k++){sum += A[i][k] * B[k][j];}C[i][j] = sum;}}return 1;} 

Method 2: Write Functions in this form.
Int matrixmultiplication (int A [] [N], int B [] [p], int C [m] [p], int Ra, int ca, int RB, int CB );
Remaining parts remain unchanged

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.