[英]Returning malloc from a function in C
我已經嘗試從函數返回 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)
然后用d
替換r
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;
}
可能的建議:
- 學習正確縮進代碼。
- 在這里詢問之前,請盡可能多次調試您的代碼。
- 打開編譯器警告(如
-Werror
、-pedantic
等)。
您的代碼完整代碼中所需的小改動如下:
#include <stdio.h>
#include <stdlib.h>
int **func1(int numrow, int numcol, int *temp, int *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[d]) * (temp[c] - word[d]) );
}
}
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.