创建单一的malloc二维数组()调用 [英] Creating 2D array in single malloc() call

查看:121
本文介绍了创建单一的malloc二维数组()调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>    
#include <stdlib.h>

#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("%d\t", 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;
    }

如果执行code,我收到以下错误消息中的对话框。

If the code is executed, I get the following error messages in a dialogbox.

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()执行时,相同的错误消息被转载。

I tried to debug in Visual Studio, when printf("\n"); statement of DisplayMatrix() is executed, same error message is reproduced.

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

If I press continue, it prints 101 to 125 as expected. In Release Mode, there is no issue !!!.

请分享您的想法。

推荐答案

C 的往往是更简单,更高效的分配一个数值矩阵释放calloc 和使用明确的指数计算...所以

In C it is often simpler and more efficient to allocate a numerical matrix with calloc and use explicit index calculation ... so

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); };

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

Then initialize and fill the matrix by computing the offset appropriately, e.g. something like

for (int i=0; i<width; i++)
  for (int j=0; j<height; j++)
    mat[i*height+j] = i+j;

如果矩阵有(如你显示),在编译时已知的尺寸,你既可以用堆分配它

if the matrix has (as you show) dimensions known at compile time, you could either stack allocate it with

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

或堆分配它。我觉得更易读,使之成为结构

or heap allocate it. I find more readable to make it a struct like

   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; i<NUM_COLS; i++)
     for (int j=0; j<NUM_ROWS, j++)
        p->matfield[i][j] = i+j;

记住的malloc 返回的未初始化的内存区的,所以你需要初始化它的全部。

Remember that malloc returns an uninitialized memory zone so you need to initialize all of it.

这篇关于创建单一的malloc二维数组()调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆