2009-05-28 90 views
2

我写了下面的代码从指针函数返回多维数组。函数的输入参数是一维数组,输出是指向多维数组的指针。从C++中的指针函数返回一个多维数组 - CLI

double **function(array< double>^ data,int width,int height) { 
    int i; 
    double **R = new double *[height]; 
    for (i=0;i<=height;i++) 
     R[i]=new double [width]; 

    // .... 

    return R; 
} 

int main(void) { 
    int M=2, N=10, i,j; 
    // define multimensional array 2x10 

    array< array<double>^ >^ input = gcnew array< array<double>^ >(M); 

    for (j=0; j<input->Length; j++) { 
     input[j]=gcnew array<double>(N);} 
     double **result1 = new double *[N]; 
     for(i=0; i<=N; i++) 
      result1[i]=new double [M]; 
     double **result2 = new double *[N]; 
     for(i=0; i<=N; i++) 
      result2[i]=new double [M]; 

     //............ 

     // send first row array of multidimensional array to function 

     result1=function(input[0],M,N); 

     // send second row array of multidimensional array to function 

     result2=function(input[1],M,N); 

     for (i=0;i<=N;i++) 
      delete R[k]; 
     delete R;}*/ 

    return 0; 
} 

我成功地建立了这个程序在Visual Studio 2008.When我调试代码,程序计算RESULT1品特可变的,但在这里函数计算RESULT2期间:

R=new double *[height]; 
for (i=0; i<=height; i++) 
    R[i]=new double [width]; 

的Visual Studio给这个错误:

An unhandled exception of type 'System.Runtime.InteropServices.SEHException' occurred in stdeneme.exe
Additional information: External component has thrown an exception.

不幸的是我不知道该怎么做。

回答

3

<=是你的问题。有效的数组索引从0N-1。分配给result1[N]是访问违规 - 这是它所抱怨的例外。

9

我一眼看到一个错误

for (i=0;i<=height;i++) 
{ 
R[i]=new double [width]; 
} 

您已经分配[R [高度] 但循环将高度+ 1

你应该写循环

for (i=0; i<height; i++) 

另一个我看到的是,当你想破坏你的矩阵,你写

delete R[k]; 

,但它应该是

delete [] R[k]; 
+0

+1:在删除错误嘛,看准 – 2009-05-28 15:00:10