How do I declare a pointer to an array of characters in C?

How do I declare a pointer to an array of characters in C?

+3


source to share


2 answers


I guess I'll give this answer piece by piece:



  • Here's a pointer to an array from char

    (I assumed an array of 10 elements):

    char (*x)[10];
    
          

    Let's break it down from the basics:

    x
    
          

    - pointer:

    *x
    
          

    into an array:

    (*x)[10]
    
          

    of char

    s:

    char (*x)[10]
    
          

  • However, most of the time when you don't need a pointer to an array, you want a pointer to the first element of the array. In this case:

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

    Either x

    or y

    is what you are looking for and are equivalent.

  • Council. Find out about cdecl

    to ease these problems for yourself.

+10


source


You can declare it as extern char (*p)[];

, but it is an incomplete type. This is, of course, because C does not have an array type, which is a complete type; only arrays of a certain size are full 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

      

+3


source







All Articles