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.
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
.
My suggestion would be to use strlen and turn on compiler optimizations.
For example, with gcc 4.7 on x86:
#include <string.h>
static const char *textMessages[3] = {
"Small text message",
"Slightly larger text message",
"A really large text message that "
"is spread over multiple lines"
};
size_t longmessagelen(void)
{
return strlen(textMessages[2]);
}
After running make CFLAGS="-ggdb -O3" example.o
:
$ gdb example.o
(gdb) disassemble longmessagelen
0x00000000 <+0>: mov $0x3e,%eax
0x00000005 <+5>: ret
I.e. the compiler has replaced the call to strlen
with the constant value 0x3e = 62.
Don't waste time performing optimizations that the compiler can do for you!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With