#include<stdio.h>
#include<stdlib.h>
struct Graph{
int V;
int E;
int **Adj;
};
struct Graph* adjMatrix(){
int u,v,i;
struct Graph *G;
G=(struct Graph*)malloc(sizeof(struct Graph));
if(!G){
    printf("Memory Error!\n");
    return;
}
printf("Enter number of nodes and number of edges:\n");
scanf("%d %d",&G->V,&G->E);
G->Adj=malloc((G->V)*(G->V)*sizeof(int));
for(u=0;u<(G->V);u++)
    for(v=0;v<(G->V);v++)
        G->Adj[u][v]=0; //This gives a segmentation fault.


printf("Enter node numbers in pair that connect an edge:\n");
for(i=0;i<(G->E);i++){
    scanf("%d %d",&u,&v);
    G->Adj[u][v]=1;
    G->Adj[v][u]=1;
}
return(G);
}
int main(){
struct Graph *G;
int i,j,count=0;
G=adjMatrix();
for(i=0;i<G->V;i++){
    for(j=0;j<G->V;j++){
        printf("%d ",G->Adj[i][j]);
        count++;
    }
    if(count==G->V)
        printf("\n");
}
return 0;
}


当我尝试在2D数组中分配值时,代码显示分段错误,即在G-> Adj [u] [v] = 0处;但我不知道这是怎么回事?因为这只是对数组的赋值。

最佳答案

#include<stdio.h>
#include<stdlib.h>
struct Graph{
int V;
int E;
int **Adj;
};
struct Graph* adjMatrix(){
int u,v,i;
struct Graph *G;
G=malloc(sizeof(struct Graph));
if(!G){
    printf("Memory Error!\n");
    return 0;
}
printf("Enter number of nodes and number of edges:\n");
scanf("%d %d",&G->V,&G->E);
//First problem was here this is how you allocate a 2D array dynamically
G->Adj=malloc((G->V)*sizeof(int*));
for(u=0;u<G->V;u++)
    G->Adj[u]=malloc((G->V)*sizeof(int));
for(u=0;u<(G->V);u++)
    for(v=0;v<(G->V);v++)
        G->Adj[u][v]=0; //This gives a segmentation fault.

    // i added some adjustment here to help you
       printf("Enter node numbers in pair that connect an edge:\n");
    for(i=0;i<(G->E);i++){
    scanf("%d %d",&u,&v);
    if(u>=G->V || v>=G->V){
    printf("Error give the right input\n");
    i--;}
    else{
    G->Adj[u][v]=1;
    G->Adj[v][u]=1;}
}
return(G);
}
int main(){
struct Graph *G;
int i,j,count=0;
G=adjMatrix();
for(i=0;i<G->V;i++){
    for(j=0;j<G->V;j++){
        printf("%d ",G->Adj[i][j]);
        count++;
    }
    if(count==G->V)
        printf("\n");
}
return 0;
}

关于c - 二维阵列动态分配中的分段故障,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54304208/

10-13 06:29