Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

c - Determining the Length of a String Literal

Given an array of pointers to string literals:

char *textMessages[] = {
    "Small text message",
    "Slightly larger text message",
    "A really large text message that "
    "is spread over multiple lines"
}

How does one determine the length of a particular string literal - say the third one? I have tried using the sizeof command as follows:

int size = sizeof(textMessages[2]);

But the result seems to be the number of pointers in the array, rather than the length of the string literal.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want the number computed at compile time (as opposed to at runtime with strlen) it is perfectly okay to use an expression like

sizeof "A really large text message that "
       "is spread over multiple lines";

You might want to use a macro to avoid repeating the long literal, though:

#define LONGLITERAL "A really large text message that " 
                    "is spread over multiple lines"

Note that the value returned by sizeof includes the terminating NUL, so is one more than strlen.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...