You already got the right answer from Mr. Blue Moon. However, to clarify about the error in your case, I want to add an elaboration.
For the code
pascal = (int **) malloc(no_of_rows * sizeof(int));
it looks like, your pascal
is of type int **
, that is, pointer to a pointer-to-int
.
So, while allocating a valid memory to pascal
, you need to allocate the size equal to the element it points to, and it points to another integer pointer
.
So, your allocation statement should be
pascal=malloc(no_of_rows * sizeof(int*));
Point to notice:
- See why not to cast the return value of
malloc()
and family in C
.
- The allocation size is calculated as
sizeof(int *)
(size of a pointer to int
) instead of sizeof(int)
.
Now, to make this statement more robust, we can (should) re-write it as
pascal=malloc(no_of_rows * sizeof*pascal);
Here, once again, two things to notice,
sizeof
is an operator, it does not need the parenthesise around its operand unless it is a type name.
- This statement, is independent of the type of
pascal
. even if you change the type of pascal
, you don't need to change the above statement.
That said, always check for the success of malloc()
before using the returned pointer.
Hope this helps.