为二维数组分配动态内存

问题描述

我正在构建一个基本的图形数据结构,其中特别是邻接矩阵函数..

我遇到了一个问题,我无法为数据类型结构图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 (将#修改为@)