malloc无法正常运行的动态内存分配。 [英] Dynamic memory allocation with malloc not working.

查看:171
本文介绍了malloc无法正常运行的动态内存分配。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<stdio.h>
#include<io.h>


void main()
{
    FILE *in;
    in = fopen("A.txt","r");
    double f;
    int i,j;
    n = 430;
    
    double **arr;
    arr = (double**)malloc(sizeof(double*)*430);
    for(i=0;i< 430; i++)
        arr[i] = (double*)malloc(sizeof(double)*430);

    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {   
            fscanf(in, "%lf",&f);
            fprintf(stdout, "%.15lf",f);

            arr[i][j] = f;
            printf("A[%d][%d] = : %f",i,j,f);
        }
        getch();
    }

    cout<<endl<<" Matrix A Fed ";
    getch();

    fclose(in);
}





我的尝试:



输入是一个包含430x430双重类型值的矩阵。

输出迭代直到i = 17并停止。

为什么会这样?

请帮助。

这是由于此处提出的更大问题引起的。

c ++ - 使用大型矩阵的动态内存分配进行LU分解。 - 堆栈溢出 [ ^ ]

推荐答案

您的程序确实有效。肯定它不健壮,你可能用一个糟糕的数据文件喂它。

略微修改它(删除了无用的 cout 电话,还有传统的 conio 标题等...)



Your program actually works. For sure it is not robust and you are probably feeding it with a bad data file.
A slightly modified it (removed the useless cout call, as well the legacy conio header, etc...)

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

int main()
{
    FILE *in;
    in = fopen("A.txt","r");
    double f;
    int i,j;
    const int n = 430;

    double **arr;
    arr = (double**)malloc(sizeof(double*)*430);
    for(i=0;i< 430; i++)
        arr[i] = (double*)malloc(sizeof(double)*430);

    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            fscanf(in, "%lf",&f);
            fprintf(stdout, "%.15lf",f);

            arr[i][j] = f;
            printf("A[%d][%d] = : %f",i,j,f);
        }
    }

    printf(" MAtrix A Fed \n");

    getchar();

    fclose(in);
}





然后我用以下程序生成的随机数喂它





then I fed it with the random numbers generated by the following program

 #include <stdio.h>
 #include <stdlib.h>
const int N = 430;

int main()
{
  int i,j;
  for (i=0; i<N; ++i)
    for(j=0; j<N; ++j)
    {
      if (j %10)
        printf(" ");
      else
        printf("\n ");

      float f = ((float)rand()/RAND_MAX);
      printf("%12g ", f);

    }
  return 0;
}







并最终获得 Matrix A Fed message。


这篇关于malloc无法正常运行的动态内存分配。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆