c - 如何在函数外传递二维指针,使指针指向的内存可以访问?

标签 c pointers malloc parameter-passing

这是一个 C 编程问题。

我需要在函数 f() 之外传输一个二维指针,以便其他函数可以访问在 f() 内部分配的内存。

但是,当 i > 1 时,我在“此处错误”处遇到了段错误。

如何做二维指针才能让输入参数真正被外部函数使用?我怀疑 *ba = (dp[0]); 有问题。

为什么?

typedef struct {
    char* al;   /* '\0'-terminated C string */
    int   sid;
} strtyp ;

strtyp *Getali(void)
{  
    strtyp  *p = (strtyp *) malloc(sizeof(strtyp )) ;
    p->al = "test al";
    p->sid = rand();
    return p; 
}

strtyp *GetNAl(void)
{
    strtyp *p = (strtyp *) malloc(sizeof(strtyp )) ;
    p->al = "test a";
    p->sid = rand();
    return p; 
}

int *getIDs2(strtyp   **ba, int *aS , int *iSz)
{
    int  *id  = (int *) malloc(sizeof(int) * 8) ;   
    *idS = 8 ; 
    int length = 10;
    int i  ;
    strtyp   **dp  = (strtyp  **) malloc(sizeof(strtyp*)*length) ;  
    for(i = 0 ; i < length ; ++i)
    {
        dp[i] = GetNAl();
        printf("(*pd)->ali is %s ", (*pd[i]).ali );
        printf("(*pd)->sid is %d ", (*pd[i]).sid );
        printf("\n");
    }
    *ba = (dp[0]); 
    for(i = 0 ; i < length ; ++i)
    {
        printf("(*ba)->ali is %s ", (*ba[i]).ali ); // error here
        printf("(*ba)->sid is %d ", (*ba[i]).sid );
        printf("\n");
    }

    *aIs = length ;
    return  id; 
}

最佳答案

如果你想在调用函数中设置一个strtype **变量,参数必须是指向这个类型的指针——strtype ***。所以你的函数看起来像:

int *getIDs2(strtyp ***ba, int *aS, int *iSz)
{
    /* ... */
    strtyp **pd  = malloc(sizeof pd[0] * length) ;  

    for(i = 0 ; i < length ; ++i)
    {
        pd[i] = GetNAl();
        printf("(*pd)->ali is %s ", pd[i]->ali );
        printf("(*pd)->sid is %d ", pd[i]->sid );
        printf("\n");
    }

    *ba = pd;

    for(i = 0 ; i < length ; ++i)
    {
        printf("(*ba)->ali is %s ", (*ba)[i]->ali );
        printf("(*ba)->sid is %d ", (*ba)[i]->sid );
        printf("\n");
    }

    /* ... */
}

...你的来电者看起来像:

strtyp **x;

getIDs2(&x, ...);

关于c - 如何在函数外传递二维指针,使指针指向的内存可以访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10117469/

相关文章:

c++ - 无法理解 new 或 malloc 如何与 BYTE* 一起工作

c - 为什么在我的centos中打印三次 'hello'?

c - sprintf 和分配内存

c++ - 退出一个函数,引用一个没有默认构造函数的类型的对象

c - 指向结构的指针

c - 棘手的指针问题

c - 在两个表之间分配数字的问题

c - 没有 malloc 或 calloc 的 free() 函数

c - 从链表中递归删除数字

c - 改进归并排序。改进 3).在输入和临时数组之间少使用一个副本