Reputation: 521
I asked my problem here The largest size of 2-D array in C and what I got answer there before declaration as duplicate by some people, I modified my code like this:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,j,n,m,p = 0 ;
int sum[100000] = {0};
scanf("%d%d%d",&n,&m,&p);
/*for ( i = 0 ; i < n ; i++ )
{
for( j = 0 ; j < m ; j++ )
{
a[i][j] = j + 1 ;
}
}*/
int **a = (int **) malloc(sizeof(int)*n);
for(i=0; i<n; i++)
{
a[i] = (int *) malloc(sizeof(int)*m);
for(i=0; i<n; i++){
for(j=0; j<m; j++){
a[i][j] = j + 1 ;
}
}
}
return 0;
}
But still I am getting the same segmentation fault.Please help me to fix it and I hope this question will not be declared as duplicate. :P
Upvotes: 2
Views: 102
Reputation: 399713
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
.
Upvotes: 5
Reputation: 4386
int **a = (int **) malloc(sizeof(int)*n);
is wrong. What you want here is an array of pointer, so you should do int **a = (int **) malloc(sizeof(int *)*n);
instead.
Upvotes: 0