Reputation: 2583
This is what I am trying to do:
const char wav_folder[] = ".\\wav";
const char search_path[strlen(wav_folder) + 6];
but the strlen part is not allowing me to create this character array. This is not compiling. Why?
Errors:
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
Upvotes: 1
Views: 2346
Reputation: 1468
The size of arrays is created at compile time. strlen()
and all other functions run at runtime.
Because of that, the compiler doesn't know how long the string will be when it allocates space in the final executable for const char search_path
.
You need to do one of the following:
use sizeof
, as in const char search_path[sizeof(wav_folder) + 6];
(thanks, guys! I forgot about that...),
manually insert the total length for search_path.
For instance,
const char search_path[13];
,
dynamically allocate an array at runtime (using new
and, when you're finished with it, freeing the memory it occupies with new
's counterpart delete
/ delete[]
,
or #define
the necessary length for searchpath
. Macros are evaluated/substituted at compile time. Therefore, you would define the necessary length like this:
#define SEARCH_PATH_LEN 13
Upvotes: 6
Reputation: 2214
The reason is exactly spelled by 1st error text - "expected constant expression"
Declaration of arrays in C/C++ requires constant expression between [
and ]
, ie an expression that can be evaluated (computed) at compile time. Result of strlen()
is not known at compile time, so it cannot be used (because it's run-time function) but you can replace it with sizeof()
:
const char search_path[sizeof(wav_folder) + 6];
EDIT (Following comments below) The constant expression is not required if array is allocated on stack, but array in the question is allocated in static memory, thus this error. Other useful details are in NathanOliver's comment below
Upvotes: 2
Reputation: 15069
if you want to dynamically allocate an array you should new operator new. This is "stack" allocation - you can't use functions to determine the size when you declare it.
The compiler wants to know the size in advance - to put it on the stack and not on the heap, and when you use the function - it can't tell what the size is (before the function is being called.
Upvotes: 2