expression did not evaluate to a constant- c++

expression did not evaluate to a constant- c++

char ansString[sizeOfRetNum]; 

Is a Variable Length Array and is not standard in C++. Some compilers like GCC allow them as an extensions but MSVS will not compile them.

In order to get a dynamic array you will need to use a pointer and new

char* ansString = new char[sizeOfRetNum];

Or better yet, rework the function to use a std::string, which handles the memory management for you.

sizeOfRetNum is not a constant value – in other words, its value is not known at compile time.

When you want to allocate memory and dont know the value until run time, you need to use dynamic memory allocation. This is done in C++ with operator new. The memory you allocate yourself with new also needs to be freed with delete or delete[].

Change char ansString[sizeOfRetNum]; to char * ansString = new char[sizeOfRetNum];. Dont forget to call delete [] ansString; before the function returns, or you will have a memory leak.

expression did not evaluate to a constant- c++

you could use malloc instead of new if you want to use it for C implementation. If you dont you could propably use std::string as @NathanOliver pointed out.

char* ansString; // ********line 10********

ansString = (char*)malloc(sizeOfRetNum*sizeof(char)); // ********line 11********

Leave a Reply

Your email address will not be published.