arrays - 如何将重复的常量字符串存储在单个指针中,同时仍然能够在编译时知道它的长度?
问题描述
我想找到一种方法将重复的常量字符串存储在一个位置。然而; 我需要在编译器级别获取该字符串的长度(这样在运行时它不会被诸如 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
有没有办法做到这一点,我不知道?
解决方案
gcc 可能能够优化 strlen() 调用以在编译时获取长度。在此处检查-foptimize-strlen
选项https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
推荐阅读
- easyphp - EasyPHP Devserver v17.0 Windows 10 安装
- python - How do you check if Python turtles overlap?
- java - Spring MVC configuration with IntelliJ IDEA
- vb.net - Making One Column of DataGridView AutoComplete for String Data
- oracle - Oracle Hierarchical Question (Find step siblings)
- php - PHP-> PDO 更新如果选择返回少于 10 行,否则插入
- python - 尽管重复,Pandas 在 jupyter notebook 中显示所有索引标签
- excel - 使用 InStr 或 Left/Right 检查反向循环中的变量
- javascript - 对象的 JSON 到达列表元素
- java - GridLayout 中的图像正在缩小