the code shows below:
The program was terminated in "printf("a[0][0] = %d\n", a[0][0]);". I think the problem relate the function init. It can't pass the "malloc 2d array" to main function. Please tell me how can i solve the passing 2d array. Thanks.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 void init(int **a, int *n) { int i, j; FILE *f; srand(time(NULL)); printf("n = "); scanf("%d", n); a = (int**)malloc((*n)*sizeof(int*)); for (i = 0; i < *n; i++) a[i] = (int*)malloc((*n)*sizeof(int)); 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 main() { int **a; int n, BestValue; init(a, &n); printf("working...\n"); printf("a[0][0] = %d\n", a[0][0]); // BestValue = FindMaxValue(a, n); // printf("%d\n", BestValue); return 0; }
[The FindMaxValue function is omitted as it doesn't relate the problem]



LinkBack URL
About LinkBacks



Anyways, if you make it something hideous like init(int ***2dArray, int n) it should work, of course at the call site you need to pass &a and in the function you would need to say something like *a = malloc, other than that it should work, although imho it would look hideous 