如何解决为二维数组分配动态内存
我正在构建一个基本的图形数据结构,其中特别是邻接矩阵函数..
我遇到了一个问题,我无法为数据类型结构图的Adj矩阵分配动态内存...
这里,大小分配出了点问题,因为当我打印它的大小它不匹配到我分配的那个...
struct Graph* AdjMatrix(){
int i,u,v;
struct Graph *G = (struct Graph *) malloc(sizeof(struct Graph));
if(G == NULL){
printf("Memory Full!\n");
return NULL;
}
printf("Enter the Number of Vertices: ");
scanf("%d",&G->V);
printf("Enter the Number of Edges: ");
scanf("%d",&G->E);
printf("Vertices: %d\t Edges: %d\n",G->V,G->E);
G->Adj = malloc(sizeof(int) * (G->V * G->V));
printf("Size of Matrix: %lu\n",sizeof(G->Adj));
for(u = 0; u <= G->V - 1; u++){
for( v = 0; v <= G->V - 1; v++){
G->Adj[u][v] = 0;
}
}
for(i = 0; i < G->E; i++){
printf("Enter the Joining Points of Vertex %d: ",i);
scanf("%d %d",&u,&v);
G->Adj[u][v] = 1;
G->Adj[v][u] = 1;
}
return G;
}
int main(){
struct Graph* node = AdjMatrix();
return 0;
}
这是图形结构
struct Graph{
int E;
int V;
int ** Adj; //For 2D Matrix
};
输出:-
Enter the Number of Vertices: 5
Enter the Number of Edges: 5
Vertices: 5 Edges: 5
Size of Matrix: 8
Segmentation fault (core dumped)
Sizeof(int)
在我的情况下 = 4(使用 64 位计算机)
所以,根据 Adj G->Adj = malloc(sizeof(int) * G->V * G->V)
的大小分配语句,sizeof(G->Adj) 应该是 4 x 25 x 25 = 100 但是,它是 8
我哪里出错了?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。