How to declare a pointer to a character array in C?

后端 未结 2 1016

How do I declare a pointer to a character array in C?

相关标签:
2条回答
  • 2021-02-04 21:51

    I guess I'll give this answer in parts:

    1. Here's a pointer to an array of chars (I assumed a 10-element array):

      char (*x)[10];
      

      Let's break it down from the basics:

      x
      

      is a pointer:

      *x
      

      to an array:

      (*x)[10]
      

      of chars:

      char (*x)[10]
      
    2. However, most of the time you don't really want a pointer to an array, you want a pointer to the first element of an array. In that case:

      char a[10];
      char *x = a;
      char *y = &a[0];
      

      Either x or y are what you're looking for, and are equivalent.

    3. Tip: Learn about cdecl to make these problems easier on yourself.

    0 讨论(0)
  • 2021-02-04 21:58

    You can declare it as extern char (*p)[];, but it's an incomplete type. This is of course because C has no "array" type generically that is a complete type; only arrays of a specific size are complete types.

    The following works:

    extern char (*p)[];
    
    char arr[20];
    
    char (*p)[20] = &arr;  // complete type now: p points to an array of 20 chars
    
    0 讨论(0)
提交回复
热议问题