Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String literals vs array of char when initializing a pointer

Tags:

People also ask

What is the difference between character array and string literal?

String refers to a sequence of characters represented as a single data type. Character Array is a sequential collection of data type char. Strings are immutable.

Are string literals pointers?

String literal as a Pointer String literals are stored just like arrays. The most important point to understand is that a string literal is a pointer to the first character of the array.

Are string literals arrays?

String literals are stored in C as an array of chars, terminted by a null byte.

What is difference between string and pointer?

A pointer contains an address . That address can come from anywhere. A string is a NUL-terminated array of characters.


Inspired by this question.

We can initialize a char pointer by a string literal:

char *p = "ab"; 

And it is perfectly fine. One could think that it is equivalent to the following:

char *p = {'a', 'b', '\0'}; 

But apparently it is not the case. And not only because the string literals are stored in a read-only memory, but it appears that even through the string literal has a type of char array, and the initializer {...} has the type of char array, two declarations are handled differently, as the compiler is giving the warning:

warning: excess elements in scalar initializer

in the second case. What is the explanation of such a behavior?

Update:

Moreover, in the latter case the pointer p will have the value of 0x61 (the value of the first array element 'a') instead of a memory location, such that the compiler, as warned, taking just the first element of the initializer and assigning it to p.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!