c - 使用函数调用分配初始化全局变量

标签 c string

我有一个简单的程序如下:

static const char* DeviceID = (char*)"my id";
int length = strlen(DeviceID);
int main(){

}

编译器抛出以下错误:

initializer element is not constant

我不知道为什么编译器无法理解我的语句:
strlen的原型(prototype)如下代码:

size_t strlen ( const char * str );

最佳答案

尝试使用 sizeof 来生成编译时间常数

#define MY_ID "my id"
static const char *DeviceID = MY_ID;  // no cast needed
int length = sizeof MY_ID - 1;        // sizeof also includes the '\0'

int main(void) {
    /* ... */
}

关于c - 使用函数调用分配初始化全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24011498/

相关文章:

c - C语言文件I/O

c - 字符串数组链表 - 段错误

string - Swift 生成器 : What is the counterpart to next()?

java - 在java中我如何删除元音是 'a'、 'e'、 'i'、 'o'和'u

ruby-on-rails - 有没有一种很好的方法来检查一个字符串是否至少包含一个字符串数组中的一个字符串?

c - 在 C 中初始化 2D/3D 数组的简写方法?

c - 如何从 C 语言的控制台输出中删除字符

c - 从邻接矩阵中查找所有路径

c# - 如何从数组中的文件中写入单词?

c++ - 为什么在比较字符串时出现错误 "no match for ' operator= =' "?