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

时间:2012-04-12 04:42:19

标签: c pointers malloc parameter-passing

这是一个C编程问题。

我需要在函数f()之外传递2-d指针,以便其他函数可以访问f()内分配的内存。

但是,当我>我在“错误在这里”时得到了分段错误1.

如何做2-d指针,以便外部函数可以真正使用输入参数?我怀疑*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; 
}

1 个答案:

答案 0 :(得分:4)

如果要在调用函数中设置strtyp **变量,则参数必须是指向此类型的指针 - 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, ...);
相关问题