1 void calc_probability(int num) 2 { 3 int i = 0, j = 0 , k = 0; 4 #define SIZE_NUM 8 5 int *array_num = NULL; 6 int *remember_num = NULL; 7 char (**array_detail)[SIZE_NUM] = NULL; //数组指针 8 int len_array = 0; 9 int count_num = 0; 10 int count = 0; 11 12 len_array = 2 * num - 1; 13 array_num = (int*)calloc(len_array, sizeof(int)); 14 array_detail = (char (**)[SIZE_NUM])calloc(len_array, sizeof(char(*))); //这里注意是sizeof(char(*)不是sizeof(char(*)[SIZE_NUM]) 15 remember_num = (int*)calloc(len_array, sizeof(int)); 16 17 for(i = 0; i < len_array; i++) 18 { 19 array_num[i] = i + 2; 20 array_detail[i] = (char(*)[SIZE_NUM])calloc(count_num + 1, sizeof(char[SIZE_NUM])); 21 } 22 23 for(i = 0; i < len_array; i++) 24 { 25 count = 0; // 计数清零 26 count_num = 0; 27 for(j = 1; j <= num; j++) 28 { 29 for(k = 1; k <= num; k++) 30 { 31 if(j + k == array_num[i]) 32 { 33 sprintf(array_detail[i] + count_num, "(%d, %d)", j, k); 34 //printf("%s", array_detail[i] + count_num); 35 count_num++; 36 count++; 37 array_detail[i] = (char(*)[SIZE_NUM])realloc(array_detail[i], (count_num + 1) * sizeof(char[SIZE_NUM])); 38 memset(array_detail[i] + count_num, 0x0, SIZE_NUM); 39 } 40 } 41 } 42 remember_num[i] = count; 43 } 44 45 for(i = 0; i < len_array; i ++) 46 { 47 printf("数字 %d 的个数是: %d ", i + 2, remember_num[i]); 48 for(j = 0; j < remember_num[i]; j++) 49 { 50 printf("%s ", array_detail[i] + j); 51 } 52 printf(" "); 53 } 54 55 56 //释放内存 57 free(remember_num); 58 remember_num = NULL; 59 60 free(array_num); 61 array_num = NULL; 62 63 for(i = 0; i < len_array; i++) 64 { 65 free(array_detail[i]); 66 array_detail[i] = NULL; 67 } 68 free(array_detail); 69 array_detail = NULL; 70 71 return; 72 73 }
错了好多次,终于改对了。