c/c++语言开发共享在单个malloc()调用中创建2D数组

#include  #include  #define MAX_ROWS 5 #define MAX_COLS 5 int globalvariable = 100; void CreateMatrix(int ***Matrix) { int **ptr; char *cp; int i = 0; *Matrix = (int**)malloc((sizeof(int*) * MAX_ROWS) + ((MAX_ROWS * MAX_COLS)*sizeof(int))); ptr = *Matrix; cp = (char*)((char*)*Matrix + (sizeof(int*) * MAX_ROWS)); for(i =0; i < MAX_ROWS; i++) { cp = (char*)(cp + ((sizeof(int) * MAX_COLS) * i)); *ptr = (int*)cp; ptr++; } } void FillMatrix(int **Matrix) { int i = 0, j = 0; for(i = 0; i < MAX_ROWS; i++) { for(j = 0; j < MAX_COLS; j++) { globalvariable++; Matrix[i][j] = globalvariable; } } } void DisplayMatrix(int **Matrix) { int i = 0, j = 0; for(i = 0; i < MAX_ROWS; i++) { printf("n"); for(j = 0; j < MAX_COLS; j++) { printf("%dt", Matrix[i][j]); } } } void FreeMatrix(int **Matrix) { free(Matrix); } int main() { int **Matrix1, **Matrix2; CreateMatrix(&Matrix1); FillMatrix(Matrix1); DisplayMatrix(Matrix1); FreeMatrix(Matrix1); getchar(); return 0; } 

如果代码被执行,我会在对话框中收到以下错误消息。

 Windows has triggered a breakpoint in sam.exe. This may be due to a corruption of the heap, which indicates a bug in sam.exe or any of the DLLs it has loaded. This may also be due to the user pressing F12 while sam.exe has focus. The output window may have more diagnostic information. 

我尝试在Visual Studio中调试printf("n"); 执行DisplayMatrix()语句,再现相同的错误消息。

如果我按下继续,它会按预期打印101到125。 在发布模式下,没有问题!!!

请分享您的想法。

    C中 ,使用calloc分配数值矩阵并使用显式索引计算通常更简单,更有效…所以

     int width = somewidth /* put some useful width computation */; int height = someheight /* put some useful height computation */ int *mat = calloc(width*height, sizeof(int)); if (!mat) { perror ("calloc"); exit (EXIT_FAILURE); }; 

    然后通过适当地计算偏移来初始化并填充矩阵,例如像

     for (int i=0; i 

    如果矩阵具有(如您所示)在编译时已知的维度,则可以使用堆栈进行分配

      { int matrix [NUM_COLS][NUM_ROWS]; /* do something with matrix */ } 

    或堆分配它。 我发现它更像是一个类似的struct

      struct matrix_st { int matfield [NUM_COLS][NUM_ROWS]; }; struct matrix_st *p = malloc(sizeof(struct matrix_st)); if (!p) { perror("malloc"); exit(EXIT_FAILURE); }; 

    然后适当填写:

      for (int i=0; imatfield[i][j] = i+j; 

    请记住, malloc返回一个未初始化的内存区域,因此您需要初始化所有内存区域

    二维数组与指向指针的指针不同。 也许你的意思

     int (*mat)[MAX_COLS] = malloc(MAX_ROWS * sizeof(*mat)); 

    代替?

    阅读本教程 。

    如果你有深入的基础知识,那么你可以直接进入第9章。

      以上就是c/c++开发分享在单个malloc()调用中创建2D数组相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/519132.html

      (0)
      上一篇 2020年12月5日
      下一篇 2020年12月5日

      精彩推荐