我有一个简单的程序如下:
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/