【问题标题】:Creating 2D array in single malloc() call在单个 malloc() 调用中创建二维数组
【发布时间】:2013-08-27 08:49:49
【问题描述】:
#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;
    }

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

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中调试,当DisplayMatrix()printf("\n");语句被执行时,同样的错误信息被重现。

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

请分享您的想法。

【问题讨论】:

  • 我很确定我以前说过,但是please don't cast the return value of malloc() in C。谢谢。
  • @unwind VS中出现错误cannot convert from 'void *' to 'int **'
  • @Jeyaram 您应该将 C 代码编译为 C,而不是 C++(正如您目前正在尝试做的那样)。
  • @H2CO3,让我检查一下。
  • 有什么理由拒绝投票????

标签: c arrays visual-studio-2010 pointers malloc


【解决方案1】:

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<width; i++)
  for (int j=0; j<height; j++)
    mat[i*height+j] = i+j;

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

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

请记住,malloc 返回一个未初始化的内存区域,因此您需要将其全部初始化。

【讨论】:

  • 但是,如果编译器自动为您执行此操作,为什么要手动执行此操作?
【解决方案2】:

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

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

改为?

【讨论】:

  • 查看 FillMatrix(),我将其作为二维数组访问。
【解决方案3】:

阅读this tutorial

一个非常好的和完整的指针教程,如果你有深入的基础知识,你可以直接进入第9章。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 2016-08-21
    • 1970-01-01
    相关资源
    最近更新 更多