Reputation: 5
This code gives a Segmentation Fault at the exact 5th line of input. If n<5 or in the debugger everything is fine.
scanf("%d %d",&n,&x);
m=(int**)malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
m[i]=(int*)malloc(2*sizeof(int));
}
for(i=0;i<n;i++)
{
scanf("%d %d",&m[i][0],&m[i][1]);
}`
Upvotes: 0
Views: 71
Reputation: 108968
assumes sizeof (int)
and sizeof (int*)
are the same
m=(int**)malloc(n*sizeof(int));
Try this
m = malloc(n * sizeof *m);
Upvotes: 4
Reputation: 12178
Your mistake: You allocate memory for int
s while you need int pointer
s
(As your m
array is going to hold pointers for other int arrays)
mistake:
m=(int**)malloc(n*sizeof(int));
correct:
m=(int**)malloc(n*sizeof(int*));
Upvotes: 0