简体   繁体   中英

C - is char* template a special type of string?

I came across a line like

char* template = "<html><head><title>%i %s</title></head><body><h1>%i %s</h1>        </body></html>";

while reading through code to implement a web server.

I'm curious as I've never seen a string like this before - is template specifying a special type of string (I'm just guessing here because it was highlighted on my IDE)? Also, how would strlen() work with something like this?

Thanks

char* template = "<html>...</html>";

is fundamentally no different than

char *s = "hello";

The name template is not special, it's just an ordinary identifier, the name of the variable. ( template happens to be a keyword in C++, but this is C.)

It would be better to define it as const , to enforce the fact that string literals cannot be modified, but it's not mandatory.

Note that template itself is not a string. It's a pointer to a string. The string itself (defined by the language as "a contiguous sequence of characters terminated by and including the first null character") is the sequence starting with "<html>" and ending with "</html>" and the implicit terminating null character.

And in answer to your second question, strlen(template) would work just fine, giving you the length of the string (81 in this case).

I imagine that there is another part of the code that uses this string to format an output string used as a page by the web server. The strlen function will return the length of the string.

Unless there's a null character somewhere in the initializer or an escape sequence using a \\ character, which there isn't, there's nothing special about this string. A % is a normal character in a string and doesn't receive special treatment. The strlen function in particular will read %i as two characters, ie % and i . Similarly for %s .

In contrast, a \\ is a special character for string and denotes an escape sequence. The \\ and the character that follows it in the string constant constitute a single character in the string itself. For example, \\n means a newline character (ASCII 10) and \\t is a tab character (ASCII 8).

This string is most likely used as a format string for printf . This function will read the string and interpret the %i and %s as format string accepting a int and a char * respectively.

char* template = "<html>...</html>";

just create a char array to store data "<html>...</html>" ,and this array name is template ,you can change this name to other name you want.When create char array,compiler will add \\0 to the end of array. strlen will calculate the length from array start to \\0 ( \\0 is no include).


I think your IDE will highlight this string is because this string is used in other place.

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