动态分配二维数组问题

来源:百度知道 编辑:UC知道 时间:2024/06/05 01:02:16
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
typedef struct
{
int m,n;
int **arr;
}MazeType;
void InitMaze(MazeType *maze,int row,int col)
{
int i,j=0;
maze->m=row;
maze->n=col;
*(maze->arr)=(int *)malloc(sizeof(int)*(row+2)); //为什么有内存问题
for(i=0;i<row+2;i++)
maze->arr[i]=(int *)malloc(sizeof(int)*(col+2)); //??
for(i=1;i<=row;i++)
for(j=1;j<=col;j++)
scanf("%d",maze->arr[i][j]);
}
int main()

{
MazeType *maze;
InitMaze(maze,3,2);
return 0;
}
编译可以通过,运行不行!

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
typedef struct
{
int m,n;
int **arr;
}MazeType;
void InitMaze(MazeType *maze,int row,int col)
{
int i,j=0;
maze->m=row;
maze->n=col;
maze->arr=(int **)malloc(sizeof(int*)*(row)); //为什么有内存问题
for(i=0;i<row+2;i++)
maze->arr[i]=(int *)malloc(sizeof(int)*(col)); //??
for(i=1;i<=row;i++)
for(j=1;j<=col;j++)
scanf("%d",&maze->arr[i][j]);
}
int main()

{
MazeType maze;
InitMaze(&maze,3,2);
return 0;
}

改成如下:
void InitMaze(MazeType *maze,int row,int col)
{
int i,j=0;
maze->m=row;
maze->n=col;

maze->arr = (int **)malloc(sizeof(int*)*(row+2)); //为什么有内存问题
// maze->arr 是指针的指针

for(i=0;i<row+2;i++)
maze->arr[i] = (int *)malloc(sizeof(int)*(col+