Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Literal string initializer for a character array

In the following rules for the case when array decays to pointer:

An lvalue [see question 2.5] of type array-of-T which appears in an expression decays (with three exceptions) into a pointer to its first element; the type of the resultant pointer is pointer-to-T.

(The exceptions are when the array is the operand of a sizeof or & operator, or is a literal string initializer for a character array.)

How to understand the case when the array is "literal string initializer for a character array"? Some example please.

Thanks!

like image 317
Tim Avatar asked Jan 10 '10 04:01

Tim


People also ask

How do you initialize a character string?

A more convenient way to initialize a C string is to initialize it through character array: char char_array[] = "Look Here"; This is same as initializing it as follows: char char_array[] = { 'L', 'o', 'o', 'k', ' ', 'H', 'e', 'r', 'e', '\0' };

Is char * A string literal?

String literals are convertible and assignable to non-const char* or wchar_t* in order to be compatible with C, where string literals are of types char[N] and wchar_t[N]. Such implicit conversion is deprecated.

How do you initialize a char array in C++?

In C++, when you initialize character arrays, a trailing '\0' (zero of type char) is appended to the string initializer. You cannot initialize a character array with more initializers than there are array elements. In ISO C, space for the trailing '\0' can be omitted in this type of information.

What is literal character strings?

A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string.


1 Answers

The three exceptions where an array does not decay into a pointer are the following:

Exception 1. — When the array is the operand of sizeof.

int main() {    int a[10];    printf("%zu", sizeof(a)); /* prints 10 * sizeof(int) */     int* p = a;    printf("%zu", sizeof(p)); /* prints sizeof(int*) */ } 

Exception 2. — When the array is the operand of the & operator.

int main() {     int a[10];     printf("%p", (void*)(&a)); /* prints the array's address */      int* p = a;     printf("%p", (void*)(&p)); /*prints the pointer's address */ } 

Exception 3. — When the array is initialized with a literal string.

int main() {     char a[] = "Hello world"; /* the literal string is copied into a local array which is destroyed after that array goes out of scope */      char* p = "Hello world"; /* the literal string is copied in the read-only section of memory (any attempt to modify it is an undefined behavior) */ } 
like image 160
Prasoon Saurav Avatar answered Oct 04 '22 11:10

Prasoon Saurav