0

一般来说,我对编程比较陌生,我正在尝试编写一些代码来处理方阵。不幸的是,我在开发的早期就被困住了,因为代码

typedef struct Matrix_t{
    float** content;
    size_t size;
} Matrix_t;

int main(int argc, char** argv) {
    Matrix_t* matr;

    initMatrix(matr,s);
    /*
    ...
    ...
    ...
    */
    return 0;
}

void initMatrix(Matrix_t* m, size_t s) {
    int i;

    m = (Matrix_t*) malloc(sizeof(Matrix_t));
    m->content = (float**) malloc(s*sizeof(float*));
    for(i=0;i<s;i++){
        m->content[i] = (float*) malloc(s*sizeof(float));
    }

    m->size = s;
}

SIGSEGV 会在 initMatrix() 完成后立即执行。使用调试器,我发现在 initMatrix() 关闭后基本上所有矩阵信息都丢失了。为什么?我该如何解决?

提前致谢。

4

2 回答 2

1

您只修改m函数中的本地自动变量。C 是一种按值传递的语言。如果您想通过地址传递,那么您必须传递地址,将形式参数声明为指向类型的指针,即使该类型已经是指针并且您正在修改的是指针本身

当您将某些内容作为输入/输出或输出参数传递时,如果您发现自己这样做:

void foo(Type *p)
{
    p = malloc(...)
}

不是在修改 指向的数据p而是在修改p自身,调用者将不知道更改。进入时存储的地址p丢失。像这样:

void foo(Type *p)
{
    *p = ....
}

正在修改p 指向的内容。也就是说,如果Type已经是一个指针类型,而你想修改它的指针本身,你必须这样做:

void foo(Type **pp) // declare a pointer-to-pointer-to-type
{
    *pp = malloc(....) // dereference to store the address returned from malloc
                       // in the pointer pointed to by pp
}

因此,最直接的解决方法是将形参声明为指向指针类型的指针,传递matrfrom的地址main()

void initMatrix(Matrix_t **pp, size_t s) 
{
    int i;

    Matrix_t *m = malloc(sizeof(Matrix_t));
    m->content = malloc(s*sizeof(float*));
    for(i=0;i<s;i++)
        m->content[i] = malloc(s*sizeof(float));
    m->size = s;
    *pp = m; // note: saving pointer to the output target
}


int main(int argc, char** argv) 
{
    Matrix_t* matr = NULL;

    initMatrix(&matr,s); // note: passing address of pointer

    /*
    ...
    ...
    ...
    */
    return 0;
}

我省略了错误检查(或者我应该说,我没有添加任何内容,因为一开始就没有)并从 中删除了不需要的演员表,您可以在此处malloc阅读更多信息。

有大约六种方法可以做到这一点,但这是最直接的你已经拥有的代码。我建议要么从函数本身返回分配作为 ret-val,或者甚至不动态分配结构本身,因为没有必要这样做。这两个我留给你考虑。

祝你好运。

于 2015-01-15T20:13:01.923 回答
1

在 main 函数中设置 matr=NULL ,然后尝试:

main(){

   Matrix_t *matr=NULL;
   /*Declare and initialize "s" variable.... */

   initMatrix(&matr,s);  /* See below...  */
   /*
     .....
   */
}

在函数 initMatrix 中使用指向 Matrix_t *m 中的指针的指针

void initMatrix(Matrix_t **m, size_t s) 
{    
     Matrix_t *aux=(Matrix_t*)malloc(sizeof(Matrix_t));

     /*check if matrix already allocated */  
     if(*m != NULL) 
     {    
         /*Make a free matrix function to free the matrix before use*/          
         free_my_matrix(m); 
         *m=NULL;
     }

     /***
        Work with aux....
        aux->content=...malloc....
     ***/

     /* make your base pointer be aux */           
     *m=aux; 
}
于 2015-01-15T20:16:09.677 回答