[英]Why getting “Segmentation fault” for the dynamically allocated 2-D array?
我正在嘗試通過使用動態分配的二維數組來生成Pascal三角形。 但是,當我嘗試運行時,出現“ Segmentation Fault”錯誤。 我在代碼中做錯了什么?
int ** generate(int A, int *number_of_rows) {
*number_of_rows = A;
int **result = (int **)malloc(A * sizeof(int *));
int i,j;
for(i=0; i < A; i++){
for(j=0; j<= i; j++){
if(i==j || j==0)
result[i][j] = 1;
else
result[i][j] = result[i-1][j] + result[i-1][j-1];
}
}
return result;
}
有人說我需要為每一行分配內存,如下所示
for (i = 0; i < A; i++)
result[i] = (int *)malloc(i * sizeof(int));
但在執行此操作后,該函數返回[0 ] [1 ] [2 ] [3 ] [4 ]
而不是[1 ] [1 1 ] [1 2 1 ] [1 3 3 1 ] [1 4 6 4 1 ]
A = 5
您已為行數組分配了內存,但尚未為每一行分配內存。
當前result[i]
指向未分配的內存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.