2012-04-12 53 views
1

这是一个C编程问题。如何在函数外部传递2维指针,以便可以访问指针指向的内存?

我需要在函数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; 
} 
+0

凡DP声明? – 2012-04-12 04:47:44

+0

对不起,错字,谢谢 – user1002288 2012-04-12 04:50:43

回答

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, ...);