用C打印2D数组

时间:2015-01-25 16:23:35

标签: c arrays

您好我有这样的代码,我想知道它为什么只打印数组的第一个元素。

int main()
{
    double** mat;
    int n;
    int m; 
    printf("Input n,m\n");
    scanf("%d %d",&n,&m);

    mat = (double**)malloc(n*sizeof(double*));
    for( int i=0; i<n; i++)
    {
        mat[i] = (double*)malloc(m*sizeof(double));
        for( int j=0; j<m; j++)
        {
            mat[i][j]= i*i+j*j;
            printf("%lf\n",mat[i][j]);

            return 0;
        }
    }
}

我还有一个问题,如果我想以矩阵格式打印,我该怎么办?

1 个答案:

答案 0 :(得分:3)

您正在循环中将控件从main返回 - 将代码更改为:

int main()
{
    //... your code as it was before - fix your loops
    int sum = 0;
    for( int i=0; i<n; i++)
    {
        mat[i] = malloc(m*sizeof(double));
        for (int j = 0; j<m; j++)
        {
            mat[i][j] = i*i + j*j;
            printf("%lf ", mat[i][j]);
            sum = sum + mat[i][j];
        }
        printf("\n");
    }
    printf("\nsum is %d.", sum);
    return 0;
}

输出:

Input n,m 3 3
0.000000 1.000000 4.000000
1.000000 2.000000 5.000000
4.000000 5.000000 8.000000

sum is 30.