gpt4 book ai didi

c - 读取使用 malloc 创建的二维数组的输入

转载 作者:行者123 更新时间:2023-11-30 15:07:07 24 4
gpt4 key购买 nike

`亲爱的 friend 们,我试图通过 malloc 使用虚拟变量 m 定义一个名为 A 的二维数组。变量 A 已初始化为 0。预计运行后会向矩阵分配新值。但这在这里不会发生。我想了解执行此操作的正确方法。我还尝试了 dynamic memory allocation in 2d array and using scanf 中描述的方法并且还避免了强制转换 malloc。这是代码

#include<stdio.h>
#include<math.h>
#include<conio.h>
#include<stdlib.h>
double** Allocate(int d1,int d2);
double** Allocate(int d1,int d2)
{
double **m;
int i,j;
m = (double**)malloc(sizeof(double*)*d1);
for(i=0;i<d1;i++)
{
m[i]=(double*)malloc(sizeof(double)*d2);
}
for(i=0;i<d1;i++)
{
for(j=0;j<d2;j++)
{
m[i][j]=0.0;
}
}
return m;
}
main()
{
int i,j;
int n=3;
float x[n],y[n];
double** A= Allocate(n,n);
for(i=0;i<=n-1;i++)
{
for(j=0;j<=n-1;j++)
{
scanf("%f",&A[i][j]);
}
}
for(i=0;i<=n-1;i++)
{
for(j=0;j<=n-1;j++)
{
printf("%f\t",A[i][j]);
}printf("\n");
}
}

最佳答案

  • 您在此处使用错误的格式说明符扫描double类型变量:

    scanf("%f",&A[i][j]);
    ^
  • 正确的格式说明符是 %lf,因此请以这种方式扫描到数组中:

    scanf("%lf",&A[i][j]);
<小时/>
  • 使用 printf() 时无需使用 %lf,因为 @Robᵩ comment中建议:

in printf(), %f is identical to %lf. Both accept a double

要了解更多信息,请参阅:click

<小时/>
  • 此外,不要使用 main(),因为它不是 main() 的有效签名,而是使用int main(void),因为在标准C中,main的唯一有效签名是:

    int main(void) //when arguments are not required
  • 还有,

    int main(int argc, char **argv)//当你需要发送参数时

要了解更多信息,请参阅:click

<小时/>
  • 并且始终确保在最后释放分配的内存

      ..........  
    printf("%lf\t",A[i][j]);
    }printf("\n");
    }

    //freeing the malloced memory
    for(i=0; i<n; i++)
    {
    free(A[i]);
    }
    free(A);

    }//end of main
<小时/>

进行上述更改后,您的 main() 函数将是:

int main(void)
{
int i,j;
int n=3;

double** A= Allocate(n,n);

for(i=0;i<=n-1;i++)
{
for(j=0;j<=n-1;j++)
{
scanf("%lf",&A[i][j]);
}
}

for(i=0;i<=n-1;i++)
{
for(j=0;j<=n-1;j++)
{
printf("%f\t",A[i][j]);
}
printf("\n");
}

for(i=0; i<n; i++)
{
free(A[i]);
}
free(A);
}

关于c - 读取使用 malloc 创建的二维数组的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38485509/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com