c - 二维阵列动态分配中的段错误

标签 c

#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/

相关文章:

c - 读取文件时如何更改数组值

c++ - OpenCV - 寻找轮廓终点?

实现简单内存池的 C 库

c - 在 C 语言中,整数作为字符出现在文件中

c - Linux 内核模块 : How to reinject packets the kernel considers as NF_STOLEN?

c - 为什么 char name[1] 可以容纳 1 个以上的字符?

c++ - 在变量中存储一个大数字并循环

c - 使用 fft2 (matlab) 和 fftw (C) 获得相同的结果

将值从一个数组复制到另一个数组

c - 如何在 C 函数中传递二维数组(矩阵)?