-1
#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 中调试,执行printf("\n");语句时DisplayMatrix(),会重现相同的错误消息。

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

请分享你的想法。

4

3 回答 3

1

Ccalloc中,分配一个数值矩阵并使用显式索引计算通常更简单、更有效......所以

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返回一个未初始化的内存区域,因此您需要对其进行初始化。

于 2013-08-27T08:56:12.427 回答
0

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

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

反而?

于 2013-08-27T08:55:45.863 回答
0

阅读本教程

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

于 2013-08-27T10:23:53.123 回答