将指针数组作为参数传递给指针

时间:2011-12-20 16:36:43

标签: c pointers multidimensional-array parameter-passing

我有以下问题,调用以下函数时将冲突初始化为NULL。

在foo结束时,冲突采用正确的值。在这个例子的情况下,*冲突应该包含值4,8和2.它根据fprintfs进行。

但是,当我在调用foo的函数中再次测试时(参见第二个代码摘录),冲突数组尚未被修改。我不知道为什么,因为我传递了一个指向数组的指针,特别是因为这种技术适用于multiDB和递归指针。任何帮助,将不胜感激。 (顺便说一句,这不是完整的代码,我只展示了相关部分)。谢谢!

int foo(
    /*==================*/
    uchar* buf, 
    uint* multiDB,
    uint* recursive,
    uint** conflict) {

select_consistent= conflict;
bool finished; 

if (((start_of_scan == 1) && (*multiDB != 1)) || ((start_of_scan== 0) && (select_consistent == NULL))) {
    fprintf(stderr, "Not doing select consistent \n "); 

    finished = TRUE; 
}
else {
    *multiDB=0; 
    fprintf(stderr, "Doing select consistent \n "); 
    finished = FALSE;
    uint n;
    int i = 0 ;
    if (select_consistent == NULL) { /*This is the first round */
          next_round = FALSE; 
        fp = popen("./algorithm '[t(1,[t(2,||),t(3,[t(8,||),t(10,||)])]).t(1,[t(4,||),t(6,||)]).t(1,[t(2,||),t(7,||)])]'", "r"); /* Issue the command.      */
        finished = FALSE; 
    }
    if (next_round == TRUE ) {
        goto parse_records; 
    }

        fscanf(fp, "%lu", &n);
        uint* conflict_ ; 
        if (n!=0) conflict_ =  (uint*) malloc(sizeof (uint) * n); 
        conflict = &conflict_; 
        next_round = TRUE; 
        int j= 0 ; 
        while (fscanf(fp, "%lu", &n) != EOF) {
            if (n == 0) {
                select_consistent=conflict; 
                goto parse_records; 
            }
            else {
                (*conflict)[j] = n; 
            }
             i++;
             j++; 

        }
        finished = TRUE;    
}
parse_records:;
int error;

.... [other code] foo2(multiDB, recursive); 

fprintf(stderr, "Array states %lu %lu \n ", (*conflict)[0], (*conflict)[1]); 
fprintf(stderr, "Array states %lu %lu \n ", (*select_consistent)[0], (*select_consistent)[1]);



return error
}

调用foo的函数是这样的:

   uint** conflict = NULL ; 
   error = foo(buf, multiDB, recursive, conflict); 
   fprintf(stderr, "value is %lu \n", (*conflict)[0]); //This is still unitialised.

1 个答案:

答案 0 :(得分:0)

看起来代码有一些指针间接问题。 conflict似乎是uint的单维数组。如果是这样,那么初始声明应该是:

uint* conflict = NULL;

然后像这样传递:

foo( ... &conflict);

然后在foo中按如下方式分配:

*conflict = (uint*)malloc( ... );

或者,如果您仍想使用conflict_,请按以下方式分配:

*conflict = conflict_;