quantum231 quantum231 - 3 months ago 10
C++ Question

Why can't I use a function call to declare the length of an array?

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

Answer

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 searchpath.

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 searchpath. 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