c - 从 C 函数返回 malloc

标签 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)

然后将

中的 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/

相关文章:

c - 使用 Google Test 测试 C 函数

c - 水平翻转位掩码

c++ - 从 ctypes 中的回调访问值

c - C语言如何重写一个函数(系统调用)?

c - 多项式操作

c - 使用 lseek 时不打印第一个字节

c - 检查输入是否为字符串的更好方法是什么?

c - 反向双链表

c - VS17 SSH Linux unistd.h

c - PAM - 找到控制标志(必需,足够)