Chinaunix首页 | 论坛 | 博客
  • 博客访问: 436473
  • 博文数量: 103
  • 博客积分: 5010
  • 博客等级: 大校
  • 技术积分: 971
  • 用 户 组: 普通用户
  • 注册时间: 2007-06-11 17:22
文章分类
文章存档

2008年(77)

2007年(26)

我的朋友

分类: C/C++

2008-01-01 12:58:33

程序的核心是实现动态生成2维矩阵(见程序)
还要注意:只要定义指针,最后都不要忘记释放指针(见程序的最后部分)

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
        int row1, col1, row2, col2;
        int i, j, k;
        int **array1, **array2, **array3;

        printf("input row1 and col1: \n");
        scanf("%d%d", &row1, &col1);
        printf("row1 = %d, col1 = %d\n", row1, col1);
        array1 = (int** )malloc(row1 * sizeof(int* ));
        for(i = 0; i < row1; i++){
                *(array1+i) = (int* )malloc(col1 * sizeof(int));
        }
        printf("input matrix1:\n");
        for(i = 0; i < row1; i++){
                for(j = 0; j < col1; j++){
                        scanf("%d", &array1[i][j]);
                }
        }
        printf("output matrix1:\n");
        for(i = 0; i < row1; i++){
                for(j = 0; j < col1; j++){
                        printf("%d\t", array1[i][j]);
                }
                printf("\n");
        }

        printf("input row2 and col2:\n");
        scanf("%d%d", &row2, &col2);
        printf("rw2 = %d, col2 = %d\n", row2, col2);
        array2 = (int** )malloc(row2 * sizeof(int* ));
        for(i = 0; i < row2; i++){
                array2[i] = (int* )malloc(col2 * sizeof(int));
        }
        printf("input matrix2: \n");
        for(i = 0; i < row2; i++){
                for(j = 0; j < col2; j++){
                        scanf("%d", &array2[i][j]);
                }
        }
        printf("output maxtrix2:\n");
        for(i = 0; i < row2; i++){
                for(j = 0; j < col2; j++){
                        printf("%d\t", array2[i][j]);
                }
                printf("\n");
        }

        printf("*************************************\n");
        array3 = (int** )malloc(row1 * sizeof(int* ));
        for(i = 0; i < row1; i++){
                array3[i] = (int* )malloc(col2 * sizeof(int));
        }

        for(i = 0; i < row1; i++){
                for(j = 0; j < col2; j++){
                        for(k = 0; k < col1; k++){
                                array3[i][j] = array3[i][j] + array1[i][k]*array2[k][j];
                        }
                }
        }

        printf("output the result: \n");
        for(i = 0; i < row1; i++){
                for(j = 0; j < col2; j++){
                        printf("%d\t", array3[i][j]);
                }
                printf("\n");
        }

        for(i = 0; i < row1; i++){
                free(array1[i]);
                free(array3[i]);
        }
        free(array1);

        for(i = 0; i < row2; i++){
                free(array2[i]);
        }
        free(array2);

        exit(0);
}

阅读(2108) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~