数组元素是C中字符串数组的变量
我正在尝试在C中初始化一个字符串数组。我想从一个变量设置数组的一个元素,但我得到一个编译器错误。 这有什么问题?
char * const APP_NAME = "test_app"; char * const array_of_strings[4] = { APP_NAME, "-f", "/path/to/file.txt", NULL };
错误是error: initializer element is not constant
。
该标准区分了const
-qualified变量和编译时间常量。
在C标准意义上,评估变量( APP_NAME
)不被视为编译时常量。 这个
char const app_name[] = "test_app"; char const*const array_of_strings[4] = { &app_name[0], "-f", "/path/to/file.txt", 0, };
将被允许,因为这不是评估app_name
而只是取其地址。
此外,您始终应该将字符串文字视为类型为char const[]
。 修改它们有不确定的行为,所以你应该保护自己不要这样做。
我能够使用gcc 4.6.3使用此语法编译它:
char* const APP_NAME = "test_app"; char* const array_of_strings[4] = { APP_NAME, "-f", "/path/to/file.txt", NULL };
如果编译器拒绝其他所有内容,您也可以尝试转换为const(风险自负):
char* const APP_NAME = "test_app"; char* const array_of_strings[4] = { (char* const)APP_NAME, "-f", "/path/to/file.txt", NULL };