Reputation: 111
I am trying to generate pascal triangle by using the 2-d array which is dynamically allocated. But when I tried to run, its giving me "Segmentation Fault" error. What I am doing wrong in the code ?
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;
}
Someone say I need to allocate memory for each row like below
for (i = 0; i < A; i++)
result[i] = (int *)malloc(i * sizeof(int));
but after doing that the function returns
[0 ] [1 ] [2 ] [3 ] [4 ]
instead of
[1 ] [1 1 ] [1 2 1 ] [1 3 3 1 ] [1 4 6 4 1 ]
for A = 5
Upvotes: 0
Views: 73
Reputation: 234875
You've allocated memory for the array of rows, but you haven't allocated memory for each row.
Currently result[i]
points to unallocated memory.
Upvotes: 1