在C中自由动态创建的3d数组

时间:2013-07-23 20:05:31

标签: c

我找到的答案似乎都没有解决我的问题。我在C中创建一个动态的3d数组,然后释放它。我可以使用嵌套的for循环存储并稍后访问存储在此数组中的数据,但在尝试使用相同的嵌套for循环设置释放它时会出现访问冲突。我哪里错了?

unsigned char ***buff1;
int r, c;
someFunction(&buff1, &r, &c);
for(int i = 0; i < r; ++i)
{
  for(int j = 0; j < c; ++j)
  {
    free(buff1[i][j]);
  }
  free(buff1[i]);
}
free(buff1);


someFunction(unsigned char**** buff, int *nR, int *nC)
{
  ...
  *buff = (SQLCHAR***)malloc(*nR * sizeof(SQLCHAR**));
  for(int i = 0; i < *nR; ++i)
  {
    (*buff)[i] = (SQLCHAR**)malloc(*nC * sizeof(SQLCHAR**));
    for(int j = 0; j < *nC; ++j)
    {
      (*buff)[i][j] = (SQLCHAR*)malloc(256);
    }
  }
}

3 个答案:

答案 0 :(得分:2)

多件事都错了:

unsigned char**** buff

这是什么,如果没有错?(好吧,好吧,不是技术上的,但风格无论如何......)

(SQLCHAR*)malloc(256);

也不是更好,因为you must not cast the return value of malloc() in C

第三个错误是你没有3D阵列。你有一个指向指针的指针。 EWWW。丑陋。为什么不分配真正的3D数组?

size_t xsize, ysize, zsize; // initialize these!
unsigned char (*arr)[ysize][zsize] = malloc(sizeof(*arr) * xsize);

然后你需要做的就是释放它:

free(arr);

老实说,这不是更好吗?

答案 1 :(得分:1)

您的代码看起来非常错误。对于初学者,您正在调用someFunction(&buff1, &r, &c),而该函数需要int而不是int *。之后你取消引用nR和nC,它们不是指针。

我猜你在编译时应该收到一些令人讨厌的警告。

答案 2 :(得分:1)

我尝试以这种方式编写代码,并且效果很好:

#include "stdio.h"
#include "stdlib.h"

int  someFunction (unsigned char**** buff, int *nR, int *nC)
{
  int i,j;
  *buff = (unsigned char ***)malloc(*nR * sizeof(char**));
  for(i = 0; i < *nR; ++i)
  {
    (*buff)[i] = (unsigned char**)malloc(*nC * sizeof(char**));
    for(j = 0; j < *nC; ++j)
    {
      (*buff)[i][j] = (unsigned char*)malloc(256);

      (*buff)[i][j][0] ='1';
    }
  }
}


int main()
{
unsigned char ***buff1;
int r = 3, c= 2,i,j;
someFunction(&buff1, &r, &c);
for( i = 0; i < r; ++i)
{
  for(j = 0; j < c; ++j)
  {
        printf("        %c",buff1[i][j][0]);
    free(buff1[i][j]);
  }
  free(buff1[i]);
}
free(buff1);
}

所以,也许你向我们展示的代码中没有发生错误。