now, i post my full code below:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define max(a,b) ((a)>(b)?(a):(b))
#define min_range 1
#define max_range 20
int **make2darray(int x, int y)
{
int i;
int **array;
array = (int**)malloc(x*sizeof(int*));
for (i = 0; i < y; i++)
array[i] = (int*)malloc(y*sizeof(int));
return array;
}
void init(int **a, int n)
{
int i, j;
FILE *f;
srand(time(NULL));
f = fopen("FindMaxValue.dat", "w");
fprintf(f, "%d\n", n);
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
a[i][j] = rand()%(max_range-min_range+1)+min_range;
fprintf(f, "%d ", a[i][j]);
}
fprintf(f, "\n");
}
fclose(f);
}
int FindMaxValue(int **a, int n)
{
int i, j;
int **valueA;
valueA = make2darray(n, n);
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
valueA[i][j] = 0;
for (i = 1; i < n; i++) {
valueA[0][i] = a[0][i-1]+a[0][i];
valueA[i][0] = a[i-1][0]+a[i][0];
}
for (i = 1; i < n; i++)
for (j = 1; j < n; j++)
valueA[i][j] = max(valueA[i][j-1], valueA[i-1][j]) + a[i][j];
return valueA[n-1][n-1];
}
int main()
{
int **a;
int n, BestValue;
FILE *f;
printf("n = ");
scanf("%d", &n);
a = make2darray(n, n);
init(a, n);
BestValue = FindMaxValue(a, n);
f = fopen("FindMaxValue.out", "w");
fprintf(f, "%d\n", BestValue);
fclose(f);
return 0;
}
at this moment, i know why it doesn't work when do this action void init(**array, n);. because the **array was going to destory(free) the memory when it had ran the init function, right? thus i have to allocate at main function.
but may you tell how that, how can i allocate 2darray at other function and then pass by refernece.