expression must have a constant value c++ string length

Cause of error expression must have a constant value c++ string length

This error expression must have a constant value c++ string length comes when a user tries to define an array in C++. It is a very common problem and is having numerous solutions. The error appears as follows:

 

Solution

Arrays are used to store several values in a single variable as opposed to having separate variables for each value. Declaring an array involves specifying the variable type, the array’s name enclosed in square brackets, and the number of elements it should hold: vehicles on a string[4];

That array’s size must be fixed before building it. A dynamically sized array must have memory allocated for it on the heap. It must be released with delete once use is complete.

 

//allocate the array
int** arr = new int*[row];
for(int i = 0; i < row; i++)
    arr[i] = new int[col];

// use the array

//deallocate the array
for(int i = 0; i < row; i++)
    delete[] arr[i];
delete[] arr;

For a fixed-size array one must declare constant: 

const int row = 8;
const int col = 8;
int arr[row][col];

 

According to the standard, the array length must be a number that can be calculated at build time in order for the compiler to allocate adequate space on the stack. You are attempting to set an array length that is unknowable at compile time in this instance.  The contents of non-constant variables assume the compiler.

So choose:

const int row = 8;

const int col= 8;

int a[row][col];

 

 

Also Read: no matching function for call to rctbridgemodulenameforclass

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *