【问题标题】:Passing pointer to array of pointers as parameter将指针作为参数传递给指针数组
【发布时间】:2012-01-24 14:40:43
【问题描述】:

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

在 foo 结束时,冲突采用正确的值。在本例中,*conflict 应包含值 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.

【问题讨论】:

    标签: c pointers multidimensional-array parameter-passing


    【解决方案1】:

    代码似乎存在一些指针间接问题。似乎conflictuint 的一维数组。如果是这样,那么初始声明应该是:

    uint* conflict = NULL;
    

    然后像这样传递它:

    foo( ... &conflict);
    

    然后在foo中分配如下:

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

    或者,如果您仍想使用conflict_,请像这样分配它:

    *conflict = conflict_;
    

    【讨论】:

      猜你喜欢
      • 2018-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-23
      • 2015-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多