-3

First, I write this code at vscode, it can be executed. Then I copy to visual studio, showing this error.

#include <Windows.h>
#include <string>
#include <cstdio>
using namespace std;

int main() {
    string s = "abcdefg";
    int arr[s.size()];
}
  • 2
    Please don't post code as an image, copy and paste the code into the post itself. – kiner_shah Nov 12 '21 at 04:13
  • 1
    Please provide the entire code instead of photo so that it will be easy to debug for other to help u. – gretal Nov 12 '21 at 04:13
  • 3
    You don't declare an array in Visual Studio. You use Visual Studio to write C++ programs, in which you might declare arrays. In your case `bitset <7> h[pt_size]` is illegal C++: it actually has SEVERAL different errors. Read the documentation for correct usage: https://www.cplusplus.com/reference/bitset/bitset/bitset/ – paulsm4 Nov 12 '21 at 04:13
  • You may want to read this: [Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/q/285551/12149471) – Andreas Wenzel Nov 12 '21 at 04:21

1 Answers1

1

In C++ the size of array must be a compile time constant(constant expression). So the following is incorrect:

int n = 10;
int arr[n]; //incorrect

Correct way to write the above is:

const int n = 10;
int arr[n]; //correct

So the error

Expression must have constant value

indicates this error since pt_size must be a constant expression(integral).

From cpp

The elements field within square brackets [], representing the number of elements in the array, must be a constant expression, since arrays are blocks of static memory whose size must be determined at compile time, before the program runs.

Jason
  • 36,170
  • 5
  • 26
  • 60