[英]Segmentation fault in 2D array Dynamic Allocation
#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; 但我不知道這有什么問題? 因為它只是對數組的賦值。
分段錯誤是由於二維數組分配方法中的錯誤引起的,正如我們在以下行中所做的那樣:
G->Adj=malloc((G->V)*(G->V)*sizeof(int));
.
它實際上分配了一個 (G->V)*(G->V) 整數的一維緩沖區,所以它不能像你想要的那樣啟用二維語法的后續訪問
簡而言之:當你想分配二維數組時,你應該首先分配一維指針數組。 在您的代碼中,應該是:
G->Adj = (int **)malloc(sizeof(int *)*G->V);
然后為每個指針分配 G->V 向量:
for(i=0; i < G->V; i++)
{
G->Adj[i] = (int *)malloc(sizeof(int)*G->V);
}
此外,一個好的做法是驗證分配結果不是 NULL(malloc 失敗),對於每個分配
有關 c 向量分配的一般說明,您可以在 方法 2 中閱讀更多內容 :“仍然可以使用 [r][c] 語法訪問”方式
除此之外,程序結束時缺少內存釋放,因此您應該以相反的順序添加對 free() 的調用(向量然后是指針)
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.