确定字符串文字的长度

Zac*_*ack 16 c arrays string literals

给定一个指向字符串文字的指针数组:

char *textMessages[] = {
    "Small text message",
    "Slightly larger text message",
    "A really large text message that "
    "is spread over multiple lines"
}
Run Code Online (Sandbox Code Playgroud)

如何确定特定字符串文字的长度 - 比如第三个?我尝试使用sizeof命令如下:

int size = sizeof(textMessages[2]);
Run Code Online (Sandbox Code Playgroud)

但结果似乎是数组中指针的数量,而不是字符串文字的长度.

Jen*_*ens 19

如果你想要在编译时计算的数字(而不是在运行时strlen),那么使用像这样的表达式是完全可以的

sizeof "A really large text message that "
       "is spread over multiple lines";
Run Code Online (Sandbox Code Playgroud)

您可能希望使用宏来避免重复长文字,但是:

#define LONGLITERAL "A really large text message that " \
                    "is spread over multiple lines"
Run Code Online (Sandbox Code Playgroud)

请注意,返回的值sizeof包括终止NUL,因此只有一个strlen.


小智 17

我的建议是使用strlen并打开编译器优化.

例如,在x86上使用gcc 4.7:

#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]);
}
Run Code Online (Sandbox Code Playgroud)

运行后make CFLAGS="-ggdb -O3" example.o:

$ gdb example.o
(gdb) disassemble longmessagelen
   0x00000000 <+0>: mov    $0x3e,%eax
   0x00000005 <+5>: ret
Run Code Online (Sandbox Code Playgroud)

即编译器已将调用替换为strlen常量值0x3e = 62.

不要浪费时间执行编译器可以为您做的优化!