分类: C/C++
2010-01-21 14:01:57
#include#include"TianShi.h" int main(void) { int matrix1[3][3]={ {1,2,3}, {4,5,6}, {7,8,9} }; int matrix2[3][3]={ {1,4,7}, {2,5,8}, {3,6,9}, }; int sum[3][3]; sum[3][3]=Sum(matrix1,matrix2); Display(sum); return 0; } TianShi.h如下: #include void Display(int planar[][3]) { int i = 0; for(;i<3;i++) { printf("\n"); int j=0; for(;j<3;j++) printf("%d\t",planar[i][j]); } printf("\n"); } int * Sum(int sth1[][3],int sth2[][3]) { int sth3[3][3]; int i = 0; int j =0; do { i++; j++; sth3[i][j]=sth1[i][j]*sth2[i][j]; }while(i<2); return sth3; } 在TianShi.h中,无论int * Sum(int sth1[][3],int sth2[][3])改成int ** 还是现在这个,编译器都要报错。 root@HelloWorld:/C1# gcc -o 2.out 2.c In file included from 2.c:2: TianShi.h: In function ‘Sum’: TianShi.h:26: warning: return from incompatible pointer type TianShi.h:26: warning: function returns address of local variable 2.c: In function ‘main’: 2.c:16: warning: assignment makes integer from pointer without a cast 这个该怎么解决呢?它讲的是什么意思?
----------------------------------------------------------------------------------
如果一个函数的目的是要产生一个新的数组,那么最好的做法是在调用函数前就生成好这个数组,然后把这个数组作为参数传给函数,在函数中修改这个数组的值. 像你这种做法,在sum函数结束后,sth3数组就作为局部变量被释放了.而且在main中,sum数组声明以后,sum就是一个常量了,又怎么能放在=左边呢. 另外,sum函数的算法也错了. 正确代码如下: void Sum(int sth1[][3],int sth2[][3],int sth3[][3]) { int i = 0; int j =0; do { sth3[i][j]=sth1[i][j]+sth2[i][j]; j++; if(j==3) {i++;j=0;} }while(i<3); } int main(void) { int matrix1[3][3]={ {1,2,3}, {4,5,6}, {7,8,9} }; int matrix2[3][3]={ {1,4,7}, {2,5,8}, {3,6,9}, }; int sum[3][3]; Sum(matrix1,matrix2,sum); Display(sum); return 0; }