处理在函数中和函数外初始化的数组

Dealing with array initialized in and out of functions

我有函数接受和 return 指针的指针(即动态分配,通过 malloc() 二维数组,因此:矩阵)。尝试在内存分配在函数内外的指针之间传递被指向两个的元素时,我遇到了麻烦。我知道这里一定有一些关于指针的非常重要的东西让我无法理解,你能给我解释一下吗?

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;

}

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

    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;

};

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

在初始化中:推测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;

由于您实际上没有给出您 运行 的代码或说明 "crash" 的含义,这可能不是您的(唯一)问题。调试帮助 post a MCVE.