I've checked that my code is properly carving out memory space, but as soon as I try to initialize my 2D array to some values and then sum up the values, I receive a segmentation fault on just a 2x2 array. I would like to eventually scale my code up to a much larger array, but I can't even get it working here. I know there are many posts about segmentation fault regarding malloc and 2D arrays, but I've been unable to find one that helps me with my problems since my C knowledge is just beginning. Any help that you can give or if you can point me to a previous question would be greatly appreciated. Thank you!
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main()
{
double sum=0;
int i,j;
int N = 2;
double **array;
array = malloc(N * sizeof(double *));
if(array == NULL) printf("Failure to allocate memory.\n");
for(i=0; i<=N; i++)
{
array[i] = malloc(N * sizeof(double));
if(array[i] == NULL) {
printf("Failed to allocate memory for arr[%d].\n", i);
exit(0);
}
}
for(i=0; i<=N; i++)
{
for(j=0; j<=N; j++)
{
array[i][j] = 1.0/(i+j);
sum = sum + array[i][j];
}
}
return(0);
}
<=or>=in C at least think twice what you are just try to express.