C: declare a constant pointer to an array of constant characters

I am trying to understand array declarations, constants, and their resulting variable types.

Allowed (by my compiler):

char s01[] = "abc" ; // typeof(s01) = char* const char s02[] = "abc" ; // typeof(s02) = const char* (== char const*) char const s03[] = "abc" ; // typeof(s03) = char const* (== const char*) 

Alternatively, we can declare the size of the array manually:

  char s04[4] = "abc" ; // typeof(s04) = char* const char s05[4] = "abc" ; // typeof(s05) = const char* (== char const*) char const s06[4] = "abc" ; // typeof(s06) = char const* (== const char*) 

How to get a result variable of type const char* const ? The following are not allowed (by my compiler):

 const char s07 const[] = "abc" ; char const s08 const[] = "abc" ; const char s09[] const = "abc" ; char const s10[] const = "abc" ; const char s11 const[4] = "abc" ; char const s12 const[4] = "abc" ; const char s13[4] const = "abc" ; char const s14[4] const = "abc" ; 

thanks

+4
source share
4 answers
 const char *const s15 = "abc"; 
+9
source

Your first typeof comments are not entirely correct. Type s01 is char [4] , and types s02 and s03 are const char [4] . When using the & or sizeof operators in an expression, and not in the subject, they will evaluate the values ​​of r char * and const char * respectively, pointing to the first element of the array.

You cannot declare them in such a way that they break up into an rvalue, which itself is const-qualified; it doesn't really make sense to have a const-qual rvalue, since rvalues ​​cannot be assigned. This is similar to what you want constant 5 , which is of type const int , not int .

+6
source

s01 and others are not types of pointers; they are types of arrays. In this sense, they are already a bit like const pointers (you cannot reassign s01 , for example, somewhere else).

+5
source

Use cdecl :

 cdecl> declare foo as constant pointer to array of constant char Warning: Unsupported in C -- 'Pointer to array of unspecified dimension' (maybe you mean "pointer to object") const char (* const foo)[] cdecl> declare foo as constant pointer to array 4 of constant char const char (* const foo)[3] cdecl> declare foo as constant pointer to constant char const char * const foo 

Array pointers are rarely used in C; usually API functions expect a pointer to the first element.

+3
source

All Articles