以下代码构建得非常好,并在 Turbo C++ 上运行。我在 MSVC2010 上构建相同的内容,它构建时没有错误,但是当我运行它(不调试运行)时,它显示
An unhandled win32 exception occurred in gentic.exe
还在调试过程中显示:
Unhandled exception at 0x00411672 in genetic.exe: 0xC0000005: Access violation writing location 0xcccccccc.
这发生在我输入行和列之后...在 *dat2=(double *)malloc(r*sizeof(double*));
(黄色箭头现在指向这些线)
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
class genetic
{
public:
int i,j,m,n;
double **dat2,**dat;
double** createarray(int r,int c)
{ int i;
*dat2=(double *)malloc(r*sizeof(double*));
for(i=0;i<r;i++)
{
dat2[i]=(double*)malloc(c*sizeof(double));
}
return dat2;
}
void input()
{
printf("enter rows \n");
scanf("%d",&m);
printf("enter cols \n");
scanf("%d",&n);
dat=createarray(m,n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
double val;
scanf("%lf",&val);
dat[i][j]=val;
}
}
}
void output()
{
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%3lf ",dat[i][j]);
}
printf("\n");
}
}
};
void main()
{
genetic g1;
g1.input();
g1.output();
getch();
}
知道为什么 MSVC 中会出现这种不同的行为吗?我们如何解决这个问题?
更新:
按照建议我更改为:
double** createarray(int r,int c)
{ int i;
double **dat2;
dat2=(double *)malloc(r*sizeof(double*));
for(i=0;i<r;i++)
{
dat2[i]=(double*)malloc(c*sizeof(double));
}
return dat2;
}
但我仍然面临问题:
Error 1 error C2440: '=' : cannot convert from 'double ' to 'double *'
最佳答案
此行不正确:
*dat2=(double *)malloc(r*sizeof(double*));
由于您尚未向 dat2
分配任何内容,因此无法取消引用它。应该是:
dat2=(double **)malloc(r*sizeof(double*));
此外,由于 dat2
不在 createarray
函数外部使用,因此最好在其中本地声明它。
关于c++ - 程序在Turbo C中运行良好,但在MSVC中失败,出现未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17667833/