0

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

7
  • 1
    Standard warning: Do not cast the result of malloc Commented Jun 2, 2015 at 14:05
  • 1
    @Eregrith I did but same result. Commented Jun 2, 2015 at 14:09
  • I know, i did not say it was your problem, it's simply a standard warning against something you should not do. Commented Jun 2, 2015 at 14:11
  • 2
    What "someone said" was correct but as you go for( j=0; j<=i; j++ ) it must be result[i] = malloc((i+1) * sizeof(int)); Commented Jun 2, 2015 at 14:11
  • 1
    @kikit Give the main function as well . Commented Jun 2, 2015 at 14:54

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.