You're telling malloc()
the wrong size.
This:
int **a = (int **) malloc(sizeof(int)*n);
should be:
int **a = malloc(n * sizeof *a);
Don't cast the result of malloc()
, and use sizeof
on the type the return pointer points at, i.e. int *
which probably has a different size than int
on your system.
Thus, thus:
a[i] = (int *) malloc(sizeof(int)*m);
should be:
a[i] = malloc(m * sizeof *a[i]);
Add code to make sure all malloc()
succeed, i.e. never return NULL
, before relying on the pointers being valid. Also make sure the initial scanf()
returns 3
, and print out the values of n
, m
and p
. Also remove sum
.