程序中动态空间二维数组的问题,在线等求解答!
#include <stdio.h>
#include <string.h>
#include <io.h>
#include <malloc.h>
#include <limits.h>
#include <stdlib.h>
#define MAX_NAME 10// 顶点字符串的最大长度+1
#define INT_MAX 99// 用整型最大值代替∞
#define MAX_VERTEX_NUM 10000// 最大顶点个数
typedef char VertexType[MAX_NAME];// 顶点数据类型及长度
typedef char LabelType[MAX_NAME];// 标签数据类型及长度
// 邻接矩阵的数据结构
typedef struct
{
int adj;// 权值
}AdjMatrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
typedef struct
{
VertexType vexs[MAX_VERTEX_NUM];// 顶点向量
AdjMatrix arcs;// 邻接矩阵
int vexnum; // 图的当前顶点数
int arcnum;// 图的当前边数
}MGraph;
MGraph graph;
// 若G中存在顶点u,则返回该顶点在图中位置;否则返回-1。
int LocateVex(MGraph G,VertexType u)
{
int i;
for(i = 0; i < G.vexnum; ++i)
if( strcmp(u, G.vexs[i]) == 0)
return i;
return -1;
}
int CreateAN(MGraph *G)
{
int i,j,k,w
char filename[13];
FILE *graphlist;
printf("请输入数据文件名(*.txt):");
scanf("%s",filename);
graphlist = fopen(filename,"r");
//filebytes = filelength ( fileno( graphlist ) ) ;
// p = ( int * ) malloc ( filebytes );
VertexType va,vb;
LabelType la;
fscanf(graphlist, "%d%d", &(*G).vexnum,&(*G).arcnum);
for(i=0;i<(*G).vexnum;++i)
fscanf(graphlist,"%s",(*G).vexs[i]);
for(i=0;i<(*G).vexnum;++i)// 初始化邻接矩阵
for(j=0;j<(*G).vexnum;++j)
{
(*G).arcs[i][j].adj=INT_MAX;// 网初始化为无穷大
}
for(k=0;k<(*G).arcnum;++k)
{
fscanf(graphlist, "%s%s%d",va,vb,&w);
i=LocateVex(*G,va);
j=LocateVex(*G,vb);
(*G).arcs[i][j].adj=(*G).arcs[j][i].adj=w;// 无向
}
fclose(graphlist);
return 1;
}
[解决办法]
就malloc 或者memalign 动态分配内存阿,
用完后 及时释放就好了
[解决办法]
仅供参考
//在堆中开辟一个4×5的二维int数组
#include <stdio.h>
#include <malloc.h>
int **p;
int i,j;
void main() {
p=(int **)malloc(4*sizeof(int *));
if (NULL==p) return;
for (i=0;i<4;i++) {
p[i]=(int *)malloc(5*sizeof(int));
if (NULL==p[i]) return;
}
for (i=0;i<4;i++) {
for (j=0;j<5;j++) {
p[i][j]=i*5+j;
}
}
for (i=0;i<4;i++) {
for (j=0;j<5;j++) {
printf(" %2d",p[i][j]);
}
printf("\n");
}
for (i=0;i<4;i++) {
free(p[i]);
}
free(p);
}
// 0 1 2 3 4
// 5 6 7 8 9
// 10 11 12 13 14
// 15 16 17 18 19