Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 403
Zack Avatar asked Sep 22 '12 07:09

Zack


2 Answers

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.

like image 79
Jens Avatar answered Oct 15 '22 15:10

Jens


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!

like image 41
privatepolly Avatar answered Oct 15 '22 16:10

privatepolly