本文運用動態數組技術編制了C語言矩陣相乘的程序.數組
1: #include <stdio.h>2: #include <stdlib.h>3:4: main()5: {6: int i,j,k,sss,**p1,**p2,**p3;
7:8: /* Request the first block of heap memory for the first matrix.*/
9: p1=(int**)malloc(2*sizeof(int*));10: for(i=0;i<=1;i++)
11: {12: p1[i]=(int*)malloc(3*sizeof(int));13: }14:15: /* Request the second block of heap memory for the second matrix.*/
16: p2=(int**)malloc(3*sizeof(int*));17: for(i=0;i<=2;i++)
18: {19: p2[i]=(int*)malloc(2*sizeof(int));20: }21:22: /* Request the third block of heap memory for the third matrix */
23: p3=(int**)malloc(3*sizeof(int*));24: for(i=0;i<=2;i++)
25: {26: p3[i]=(int*)malloc(3*sizeof(int));27: }28:29: /* Assign the first matrix. */
30: printf("The first matirx:\n");31: for(i=0;i<=1;i++)
32: {33: for(j=0;j<=2;j++)
34: {35: p1[i][j]=(i+1)*10+(j+1);36: printf("%d\t",p1[i][j]);37: }38: printf("\n");39: }40:41: printf("The second matirx:\n");42: /* Assign the second matrix. */
43: for(i=0;i<=2;i++)
44: {45: for(j=0;j<=1;j++)
46: {47: p2[i][j]=(i+1)*10+(j+1)*1;48: printf("%d\t",p2[i][j]);49: }50: printf("\n");51: }52:53: printf("The product:\n");54: /* Calculate the product of the two matrice. */
55: for(i=0;i<=1;i++)
56: {57: for(j=0;j<=1;j++)
58: {59: sss=0;60: for(k=0;k<=2;k++)
61: {62: sss=sss+(p1[i][k])*(p2[k][j]);63: }64: p3[i][j]=sss;65: printf("%d\t",p3[i][j]);66: }67: printf("\n");68: }69: }70:
運行結果:spa
The first matirx:
11 12 13
21 22 23
The second matirx:
11 12
21 22
31 32
The product:
776 812
1406 1472 code