qua*_*231 1 c++ arrays char strlen
这就是我想要做的:
const char wav_folder[] = ".\\wav";
const char search_path[strlen(wav_folder) + 6];
Run Code Online (Sandbox Code Playgroud)
但是strlen部分不允许我创建这个字符数组.这不是编译.为什么?
错误:
Error 1 error C2057: expected constant expression c:\users\hassan\documents\cpp\dir_search\dir_search\dir_search\source.cpp 15 1 dir_search
Error 2 error C2466: cannot allocate an array of constant size 0 c:\users\hassan\documents\cpp\dir_search\dir_search\dir_search\source.cpp 15 1 dir_search
Error 3 error C2734: 'search_path' : const object must be initialized if not extern c:\users\hassan\documents\cpp\dir_search\dir_search\dir_search\source.cpp 15 1 dir_search
Error 4 error C2133: 'search_path' : unknown size c:\users\hassan\documents\cpp\dir_search\dir_search\dir_search\source.cpp 15 1 dir_search
Run Code Online (Sandbox Code Playgroud)
数组的大小是在编译时创建的.strlen()和所有其他函数在运行时运行.
因此,编译器不知道字符串在最终可执行文件中分配空间时的长度const char search_path.
您需要执行以下操作之一:
使用sizeof,如const char search_path[sizeof(wav_folder) + 6];(谢谢,伙计们!我忘记了......),
手动插入总长度,search_path.例如
const char search_path[13];,
在运行时动态分配一个数组(使用new和,当你完成它时,释放它占用的内存与new对应的delete/ delete[],
或者 #define必要的长度searchpath.在编译时评估/替换宏.因此,您可以像这样定义必要的长度:
#define SEARCH_PATH_LEN 13