Hi,
I'm trying to write a simple application to initialise a 2d array, and later manipulate the values by performing some maths on the values.
I started out trying to use the declaration: double array[5][5], which was working until i needed to pass the array into functions. I then thought i would need to use a double pointer: double **array for this purpose. The application successfully initialises the array with random values, but i am unable to access the values in a later function, "relax".
I have a suspicion that i am initialising the array using call by value, meaning the global array variable in main is not getting set, resulting in a 'bus error'. If this is the case, i am not sure how to transform this to use call by reference? Of course the problem may be something completely different.
Thanks in advance.
--------------------------------------------------------------------------------
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main (int argc, const char * argv[]) {
double **a;
int i, j, n;
srand(time(0));
n=5;
a = createMatrix(a, n);
//double val = a[1][1];
relax(a);
}
void createMatrix(double **a, int n)
{
int i;
a = calloc(n, sizeof(double *));
for (i = 0; i < n; ++i)
{
a[i] = calloc(n, sizeof(double));
}
populateMatrix(a, n);
}
void populateMatrix(double **a, int n)
{
int i,j;
printf("\n---------------------------------------------------------------\n");
for (i = 0; i < n; ++i)
{
for (j = 0; j < n; ++j) {
a[i][j] = (double) (rand() % 10 + 1);
//printf("a[%d][%d] = %lf\n", i, j, a[i][j]);
printf("%lf ", a[i][j]);
}
printf("\n---------------------------------------------------------------\n");
}
printf("a[%d][%d] = %lf\n", 1, 1, a[1][1]);
}
void relax(double **a)
{
int i,j;
i=1;
j=1;
a[i][j] = 725;
printf("a[%d][%d] = %lf\n", i, j, a[i][j]);
printf("a[0][1] = %lf", a[0][1]);
printf("a[1][2] = %lf", a[1][2]);
printf("a[1][0] = %lf", a[1][0]);
printf("a[2][1] = %lf", a[2][1]);
double val = (a[0][1] + a[1][2] + a[1][0] + a[2][1])/4;
printf("relax: a[1][1] = %lf", val);
}