我希望在编译时找到 C 字符串文字的长度。 给定定义:
static const char * const header_left[] =
{
" | | Raw | Raw |",
" | | Start | End |",
"Interval#| Duration | Point | Point |",
"---------+----------+-------+-------+",
};
const unsigned int rows_in_header = sizeof(header_left) / sizeof(header_left[0]);
如何在不使用 strlen
的情况下找到字符串文字 header_left[2]
的长度?
在这个问题中,Determining the Length of a String Literal , 有注释将数组声明为 header_left[][4]
。我不喜欢使用这种声明,因为在不改变数量常量的情况下,字符串的数量往往会发生变化。我喜欢让编译器计算字符串的数量(参见 rows_in_header
定义)和每个字符串的长度。
这适用于嵌入式系统,字符串 block 写入到串行端口。串口函数将指向数据的指针和数据的长度作为参数。串行端口代码针对 block 写入进行了优化。最好不要使用 strlen
,因为那会浪费性能时间。
我在 ARM7TDMI 平台上使用 C99 和 IAR Embedded Workshop。
我包含了 c++
标签,因为这也涉及 C++,我们将在首次产品发布后将代码迁移到 C++。
最佳答案
如果您愿意,stringref 类可以处理这个问题。它似乎比大多数其他答案更简单,并且处理行长度不同的情况:
struct stringref {
//this is for convenience, but isn't used in this sample
stringref(const char* p, size_t l=0) :ptr(p), len(l?l:strlen(p)) {}
//construct from string literals
template<size_t l> stringref(const char(&p)[l]) :ptr(p), len(l) {}
//convert to const char*
operator const char*() const {return ptr;}
const char* get() const {return ptr;}
//retrieve the length
size_t length() const {return len;}
private:
const char* ptr;
size_t len;
};
stringref header_left[] =
{
" | | Raw | Raw | ",
" | | Start | End | ",
"Interval#| Duration | Point | Point | ",
"---------+----------+-------+-------+",
};
int main()
{
const char* ptr = header_left[0]; //conversion possible
printf("%d\n", header_left[0].length());
printf("%d\n", header_left[1].length());
printf("%d\n", header_left[2].length());
printf("%d\n", header_left[3].length());
}
关于c++ - 字符串文字数组中字符串文字的编译时间大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16323677/