简体   繁体   中英

How can a string literal be dereferenced?

The following code will compare the character S with the first element of string literal "Stack" ,

As per my understanding, only pointers can be dereferenced, but this string literal works like a pointer?

#include <stdio.h>
int main() {
    if('S'==*"Stack")
        printf("equal");
}

“String literal” is a name for a thing in source code, like “keyword” is a name for key words like int or switch in source code.

When a string literal appears in source code, an array of characters is created and filled with the characters of the string literal, plus a terminating null character (C 2018 6.4.5 6).

When an array is used in an expression, other than as the operand of sizeof , the operand of unary & , or as a string literal used to initialize some other array, it is automatically converted to a pointer to its first element (C 2018 6.3.2.1 3).

Thus, when "Stack" appears in source code, it results in a pointer to “S”, so *"Stack" is a char with the value for “S”.

Similarly, "Stack"[1] is a char with the value for “t”.

In C, a string literal is an array , since strings in C are arrays of characters.

In C, when an array appears in an expression, almost without exception, what you get (the "value" of the array for the purposes of evaluating that expression) is a pointer to the array's first element .

So if you say

int a[10];
*a = 7;

, that does precisely the same thing that a[0] = 7 would do. And, having done that, you could test it by saying if(*a == 7) .

And the situation is 100% analogous to the example you posted. The string literal "Stack" is an array, so when you use it in an expression, its effective value is a pointer to its first element.

Expanding things out to see the "hidden" internal steps, it works identically to what would have happened if you had written

char stringliteral[] = "Stack";        /* the string literal is actually an array */
char *temporary_pointer;
temporary_pointer = &stringliteral[0]; /* we implicitly get a pointer to the array's first element */
if('S' == *temporary_pointer)
    ...

Addendum: Another demonstration of this fact, that a string literal is actually an array, crops up if you're writing code to convert a number to its string representation. Any integer-to-string algorithm inevitably ends up computing digit values which it must convert to the corresponding characters. If you're working in base 10 or less, you can convert digits to characters by simply adding an offset: dig + '0' . But another way, which works for eg hexadecimal digits as well, is "0123456789abcdef"[dig] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM