In C, what does a variable declaration with two asterisks (**) mean?

后端 未结 5 1836
我在风中等你
我在风中等你 2020-12-12 20:57

I am working with C and I\'m a bit rusty. I am aware that * has three uses:

  1. Declaring a pointer.
  2. Dereferencing a pointer.
  3. Multi
5条回答
  •  生来不讨喜
    2020-12-12 21:28

    It declares aPointer as a pointer to a pointer to char.

    Declarations in C are centered around the types of expressions; the common name for it is "declaration mimics use". As a simple example, suppose we have a pointer to int named p and we want to access the integer value it's currently pointing to. We would dereference the pointer with the unary * operator, like so:

    x = *p;
    

    The type of the expression *p is int, so the declaration of the pointer variable p is

    int *p;
    

    In this case, aPointer is a pointer to a pointer to char; if we want to get to the character value it's currently pointing to, we would have to dereference it twice:

    c = **aPointer;
    

    So, going by the logic above, the declaration of the pointer variable aPointer is

    char **aPointer;
    

    because the type of the expression **aPointer is char.

    Why would you ever have a pointer to a pointer? It shows up in several contexts:

    • You want a function to modify a pointer value; one example is the strtol library function, whose prototype (as of C99) is
      long strtol(const char * restrict str, char ** restrict ptr, int base);  
      
      The second argument is a pointer to a pointer to char; when you call strtol, you pass the address of a pointer to char as the second argument, and after the call it will point to the first character in the string that wasn't converted.

    • Remember that in most contexts, an expression of type "N-element array of T" is implicitly converted to type "pointer to T", and its value is the address of the first element of the array. If "T" is "pointer to char", then an expression of type "N-element array of pointer to char" will be converted to "pointer to pointer to char". For example:
      
          void foo(char **arr)
          {
            size_t i = 0;
            for (i = 0; arr[i] != NULL; i++)
              printf("%s\n", arr[i]);
          }
      
          void bar(void)
          {
            char *ptrs[N] = {"foo", "bar", "bletch", NULL};
            foo(ptrs); // ptrs decays from char *[N] to char **
          }
      
      

    • You want to dynamically allocate a multi-dimensional array:
      
      #define ROWS ...
      #define COLS ...
      ...
      char **arr = malloc(sizeof *arr * ROWS);
      if (arr)
      {
        size_t i;
        for (i = 0; i < ROWS; i++)
        {
          arr[i] = malloc(sizeof *arr[i] * COLS);
          if (arr[i])
          {
            size_t j;
            for (j = 0; j < COLS; j++)
            {
              arr[i][j] = ...;
            }
          }
        }
      }
      

提交回复
热议问题