处理数组初始化和退出函数

时间:2015-01-24 01:19:24

标签: c++ arrays pointers casting malloc

我有一个函数,它接收和返回指针的指针(即动态分配,通过malloc()2d数组,因此:矩阵)。当尝试在指针内部指向元素时,我遇到了麻烦,指针的内存分配在函数内部和外部。我知道这里的指针必须有一些非常重要的东西让我望而却步,请你指点一下吗?

double** initialize(int N,int M); // ..allocates memory for me and gives me back the "pointer to a matrix".

double** A = initialize(int N,int M);

double** myfun(double** A){

double** P;
P = initialize(int L,int K);

// .. I wanna write element "of" A to the newly allocated memory pointed by P
// .. this crashes

P[l][k] = A[i][j];

// .. this works fine
double temp;
temp = A[i][j];

P[l][k] = temp;

return P;

}

编辑:这是初始化的工作原理。我不想在这里调试代码或构建适当的矩阵,我只想了解这个实例中指针的具体行为。这里的代码是essentialy伪代码。

    double** A = initialize(int N,int M){ // .. i.e. something along the line of:

 double** A;
      A =  (double**) malloc((N)*sizeof(double*));
      A[0] =  (double*) malloc(area*sizeof(double));
      A[1] = A[0] + 1;
      for (int i=2; i<N; i++) A[i] = A[i-1] + M;

      /* Initialize to zero */
      for (int i=0; i<N; i++) for (int j=0; j<M; j++) A[i][j] = 0;

};

1 个答案:

答案 0 :(得分:0)

您的示例用法与我们猜测的预期用途一致。

初始化:大概area的值为N * M。在

  A[1] = A[0] + 1;
  for (int i=2; i<N; i++) A[i] = A[i-1] + M;

在第一行+ 1应为+ M。你应该写

for (int i=1; i<N; i++) A[i] = A[i-1] + M;

你还需要

return A;

由于您实际上没有给出您运行的代码或说“崩溃”的含义,这可能不是您的(唯一)问题。有关调试帮助,请发布MCVE