首页 文章

你能在函数中返回一种指向指针的指针吗?

提问于
浏览
3

我知道你可以从函数返回一种指针 . 恩 . void *foo() 你能在函数中返回一种指向指针的指针吗?恩 . void **foo2()

以下是有关我的问题的更多信息:

我尝试将ptr-to-ptr,tmp2分配给blocks [i] [j],然后返回tmp2 . blocks [i] [j]也是ptr-to-ptr .

我很困惑将ptr操纵到ptr-to-ptr:我不确定 return ((tmp2+i)+j); 是否是 printf("2---%d\n", **tmpPtr2); 行的分段错误的原因 . 要调试,我尝试打印: printf("%d\n", *( (*(tmp2+i)) +j) ); 但是,它会导致新的分段错误 .

#include <stdio.h>
#include <stdlib.h>

int **blocks, **tmp2;
int n = 10;

int **findBlock2(int b){
    int i, j ;

    for (i=0; i<n; i++){
        for (j=0; j<n; j++){
            if (blocks[i][j]==b){
                printf("%d\n", blocks[i][j]);

                //Segmentation fault
                printf("%d\n", *((*(tmp2+i))+j) );

                return ((tmp2+i)+j);
            }
        }
    }
    return NULL;
}

int main(int argc, const char * argv[]) {
    int i, j;
    int **tmpPtr2;

    //allocate memory space and assign a block to each index
    blocks=malloc(n * sizeof *blocks);
    for (i=0; i<n; i++) {
        blocks[i]=malloc(n * sizeof(*blocks[i]));
        blocks[i][0]=i;
    }

    if ((tmpPtr2=findBlock2(4))==NULL)    return -1;

    //Segmentation Fault
    printf("2---%d\n", **tmpPtr2);

    return 0;
}

更新回答我的问题:

(1)在findBlock2()的顶部添加t tmp2=blocks; 删除了两个段错误 .

(2) return ((tmp2+i)+j); 显示了如何操作指向ptr-to-ptr或2D数组的ptr-to-ptr

(3) printf("%d\n", *( (*(tmp2+i)) +j) ); 显示了如何做(2)并取消引用它 .

希望它能帮助别人

3 回答

  • 0

    是的,就像你对任何指针变量一样 .

    #include <stdio.h>
    #include <stdlib.h>
    
    int ** function(){
        int ** matrix = malloc(sizeof(int*));
        *matrix = malloc(sizeof(int));
        matrix[0][0] = 5;
        return matrix;
    }
    
    int main()
    {
        int **matrix = function();
        printf("%d",matrix[0][0]);
        free(matrix[0]);
        free(matrix);
        return 0;
    }
    

    添加到其他部分 . 在您的函数 findBlock2 中,除了访问已经指出的无效引用之外,您的目标似乎是返回对满足 if 语句的块的引用 . 如果是这种情况,那么返回指向 int* 的指针就足够了 .

    int *findBlock2( int b )

    /////////////////
    

    return ( *(blocks+i)+j );

  • 1

    答案是肯定的 . 请参考以下代码:

    #include <stdio.h>
    #include <malloc.h>
    
    void ** foo2(void){
        int **p = malloc(sizeof(*p));
        return (void**)p;
    }
    
    int main(void) {
        printf("%p\n", foo2());
        return 0;
    }
    

    结果是(在我的 32-bit 平台中):

    0x80e9008
    
  • 0

    您可能想要一个二维数组,而不是一些缓慢,碎片化的查找表 . 在这种情况下,请这样做:

    #include <stdlib.h>
    
    void* alloc_2D (size_t x, size_t y)
    {
      return malloc (sizeof (int[x][y]));
    }
    
    int main (void)
    {
      const size_t X = 5;
      const size_t Y = 3;
    
      int (*arr_2D)[Y] = alloc_2D(X, Y); 
    
     // X dimension was omitted in declaration to make array syntax more intuititve:
    
      arr_2D[i][j] = something;
    
      ...
      free(arr_2D);
    }
    

相关问题