首页 > 解决方案 > 如何将重复的常量字符串存储在单个指针中,同时仍然能够在编译时知道它的长度?

问题描述

我想找到一种方法将重复的常量字符串存储在一个位置。然而; 我需要在编译器级别获取该字符串的长度(这样在运行时它不会被诸如 strlen() 之类的函数找到)。如图所示,我知道一种方法可以分别进行这些操作。

使用指针将重复的字符串存储在单个地址中:

const char *a = "Hello world.";
const char *b = "Hello world.";
printf("a %s b\n", a == b ? "==" : "!="); // Outputs "a == b" on GCC

在编译时获取字符串的长度:

const char c[] = "Hello world.";
printf("Length of c: %d\n", sizeof(c) - 1); // Outputs 12 on GCC

虽然似乎没有办法将两者结合起来:

const char *d = "Hello world.";
printf("Length of d: %d\n", sizeof(d)); // Outputs the size of the pointer type; 8 on 64-bit computers

const char e[] = "Hello world.";
const char f[] = "Hello world.";
printf("e %s f\n", e == f ? "==" : "!="); // Outputs "e != f" on GCC

const char *g[] = {"Hello world."};
const char *h[] = {"Hello world."};
printf("g %s h\n", g == h ? "==" : "!="); // Outputs "g != h"
printf("Length of g: %d\n", sizeof(g[0])); // Outputs pointer type size

有没有办法做到这一点,我不知道?

标签: arrayscstringpointersgcc

解决方案


gcc 可能能够优化 strlen() 调用以在编译时获取长度。在此处检查-foptimize-strlen选项https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html


推荐阅读