带malloc的垃圾值

带malloc的垃圾值,c,malloc,garbage,C,Malloc,Garbage,我想以双精度存储数字,但它打印的是垃圾值。我尝试将malloc更改为calloc,即使这样我也得到了垃圾值。有人能解释为什么会这样吗 #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { double **mat1; int i,j,k,size; printf("Enter the matrix size"); scanf("%d",&a

我想以双精度存储数字,但它打印的是垃圾值。我尝试将malloc更改为calloc,即使这样我也得到了垃圾值。有人能解释为什么会这样吗

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

int main() {
    double **mat1;
    int i,j,k,size;

    printf("Enter the matrix size");
    scanf("%d",&size);

    mat1 = (double**)malloc(size*sizeof(double*));
    for(i=0;i<size;i++)
        mat1[i]=(double*)malloc(size*sizeof(double));

    if(mat1 != NULL) {
        // Enter the input matrix
        printf("\nEnter the elements of matrix\n");
        for(i=0;i<size;i++){
            for(j=0;j<size;j++)
                scanf("%d",&mat1[i][j]);
        }

        //Printing Input Matrix
        printf("\n Entered Matrix 1: \n");
        for(i=0;i<size;i++){
            for(j=0;j<size;j++)
                printf("%d ",mat1[i][j]);
        }
    }
    else {
        printf("error");
    }
}

除了评论之外,如果您没有检查,还有几个与验证相关的问题会困扰您。首先,您在代码中面临两个这样的问题,这两个问题每次都适用

1始终验证每个分配。正如@AnT所指出的,检查ifmat1!=NULL已经太晚了。您必须检查每个分配。e、 g

/* allocate & VALIDATE */
if (!(mat1 = malloc (size * sizeof *mat1))) {
    fprintf (stderr, "error: virtual memory exhausted.\n");
    return 1;
}

示例使用/输出


祝你编码顺利。如果您还有其他问题,请告诉我。

您对scanf和printf使用了错误的说明符,%d用于有符号整数,请尝试使用%gAlso,我听说在C中强制转换malloc返回值不是一个好主意。您的代码有相关的警告,但必须打开警告。通常这是通过墙来完成的。重新编译警告,修复它们,然后查看是否仍然存在问题。正在检查ifmat1!=此时为NULL已经太晚了,因为您已经在上一个周期中尝试访问mat1[i]。另外,不要强制转换malloc的结果。最后,在函数的开头堆积所有变量声明不是一个好的做法。感谢您的详细解释。很高兴它有所帮助。您还可以使用perror代替fprintf来报告分配失败错误,并将设置errno。e、 如果!mat1=malloc size*sizeof*mat1{perror malloc-mat1;…关键是验证每个分配,就像验证每个用户输入一样:
for (i = 0; i < size; i++)  /* allocate & VALIDATE */
    if (!(mat1[i] = malloc (size * sizeof **mat1))) {
        fprintf (stderr, "error: virtual memory exhausted.\n");
        return 1;
    }
/* Enter the input matrix */
printf ("\nEnter the elements of matrix\n");
for (i = 0; i < size; i++) {
    for (j = 0; j < size; j++)
        if (scanf ("%lf", &mat1[i][j]) != 1) {  /* VALIDATE */
            fprintf (stderr, "error: invalid conversion.\n");
            return 1;
        }
}
/* Printing Input Matrix */
printf ("\n Entered Matrix 1: \n");
for (i = 0; i < size; i++) {
    for (j = 0; j < size; j++)
        printf (" %6.2lf", mat1[i][j]);
    putchar ('\n');
}
$ ./bin/matrixdbg
Enter the matrix size: 2

Enter the elements of matrix
1.1
2.2
3.3
4.4

 Entered Matrix 1:
   1.10   2.20
   3.30   4.40