How do pointer to pointers work in C?

前端 未结 14 1259
渐次进展
渐次进展 2020-11-22 02:03

How do pointers to pointers work in C? When would you use them?

14条回答
  •  [愿得一人]
    2020-11-22 02:58

    How do pointers to pointers work in C?

    First a pointer is a variable, like any other variable, but that holds the address of a variable.

    A pointer to a pointer is a variable, like any other variable, but that holds the address of a variable. That variable just happens to be a pointer.

    When would you use them?

    You can use them when you need to return a pointer to some memory on the heap, but not using the return value.

    Example:

    int getValueOf5(int *p)
    {
      *p = 5;
      return 1;//success
    }
    
    int get1024HeapMemory(int **p)
    {
      *p = malloc(1024);
      if(*p == 0)
        return -1;//error
      else 
        return 0;//success
    }
    

    And you call it like this:

    int x;
    getValueOf5(&x);//I want to fill the int varaible, so I pass it's address in
    //At this point x holds 5
    
    int *p;    
    get1024HeapMemory(&p);//I want to fill the int* variable, so I pass it's address in
    //At this point p holds a memory address where 1024 bytes of memory is allocated on the heap
    

    There are other uses too, like the main() argument of every C program has a pointer to a pointer for argv, where each element holds an array of chars that are the command line options. You must be careful though when you use pointers of pointers to point to 2 dimensional arrays, it's better to use a pointer to a 2 dimensional array instead.

    Why it's dangerous?

    void test()
    {
      double **a;
      int i1 = sizeof(a[0]);//i1 == 4 == sizeof(double*)
    
      double matrix[ROWS][COLUMNS];
      int i2 = sizeof(matrix[0]);//i2 == 240 == COLUMNS * sizeof(double)
    }
    

    Here is an example of a pointer to a 2 dimensional array done properly:

    int (*myPointerTo2DimArray)[ROWS][COLUMNS]
    

    You can't use a pointer to a 2 dimensional array though if you want to support a variable number of elements for the ROWS and COLUMNS. But when you know before hand you would use a 2 dimensional array.

提交回复
热议问题