三天以来,我一直在尝试从函数返回 malloc,但并不高兴。
我的代码如下,我想做的是传递两个一维数组并执行矩阵计算,然后以二维数组返回结果。代码如下:
int **func1(numrow, numcol, *temp, *word){
int i, c, d;
int **pointer;
pointer = (int**)malloc( numrow * sizeof(int*);
for(i=0; i<numrow; i++){
pointer[i] = (int*)malloc( numcol * sizeof(int*) );
}
for ( c = 0 ; c < numrow ; c++ )
for ( d = 0 ; d < numcol ; d++ )
pointer[c][d] =( (temp[c] - word[r]) * (temp[c] - word[r]) );
return pointer;
}
int main(){
int **poi, r, c, numcol, numrow;
int templet[8] = {1, 1, 1, 1, 3, 4, 4, 4 };
int newWord[8] = {1, 1, 4, 4, 4, 5, 0, 0 };
printf("please enter the number of rows:\n");
scanf("%d%d",&numrow, &numcol);
poi = func1(numrow, numcol, templet, newWord );
for(r=0; r<numrow; r++)
for(c=0; c< numrow; c++)
printf("%d\n",*(*(poi + r) + c));
return 0;
}
最佳答案
首先将函数声明符更改为
int **func1(int numrow, int numcol, int *temp, int *word)
然后将
中的r
替换为 d
pointer[c][d] =( (temp[c] - word[r]) * (temp[c] - word[r]));
最后
printf("%d\n",*(*(poi + r) + c));
至
printf("%d\n",poi[r][c]);
更正的代码:
int **func1(int numrow, int numcol, int *temp, int *word) {
int i, c, d;
int **pointer;
pointer = malloc(numrow * sizeof(int*));
for (i = 0; i < numrow; i++){
pointer[i] = malloc(numcol * sizeof(int));
}
for ( c = 0 ; c < numrow ; c++ )
for ( d = 0 ; d < numcol ; d++ )
pointer[c][d] =( (temp[c] - word[d]) * (temp[c] - word[d]));
return pointer;
}
int main(void){
int **poi, r, c, numcol, numrow;
int templet[8] = {1, 1, 1, 1, 3, 4, 4, 4 };
int newWord[8] = {1, 1, 4, 4, 4, 5, 0, 0 };
printf("please enter the number of rows and columns:\n");
scanf("%d%d", &numrow, &numcol);
poi = func1(numrow, numcol, templet, newWord);
for (r = 0; r < numrow; r++)
for(c = 0; c numrow; c++)
printf("%d\n",poi[r][c]);
return 0;
}
<小时/>
可能的建议:
- Learn to indent code properly.
- Debug your code many times as possible before asking here.
- Turn on your compiler warnings (like
-Werror
,-pedantic
etc).
关于c - 从 C 函数返回 malloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22579467/