Good day. Faced an error "Expression must have a constant value" when creating an array. Find this question c++ array - expression must have a constant value , but these tips didn't solve the problem. Please help and I'm sorry for such requests, I just started to learn C ++
Code:
#include <iostream>
#include <math.h>
#include <cstdlib>
#include <string>
#include <sstream>
#include <conio.h>
#include <random>
int main()
{
int userInput = 0, sumEvenIndexElements = 0, sumElementsBeetwenZero = 0;
bool checkZeroElements = false;
std::cout << "Write array length:" << std::endl;
std::cin >> userInput;
const int lengthOfArray = userInput;
int numbers [lengthOfArray];
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(-10, 10);
for (int index = 0; index < lengthOfArray; index++)
{
numbers[index] = new int[distribution(generator)];
std::cout << numbers << std::endl;
if (index % 2 == 0)
{
sumEvenIndexElements += *numbers[index];
}
}
std::cout << "Sum even index elements: " << sumEvenIndexElements << std::endl;
for (int index = 0; index < lengthOfArray; index++)
{
numbers[index] = new int[distribution(generator)];
if (numbers[index] == 0)
{
checkZeroElements = !checkZeroElements;
}
if (checkZeroElements)
{
sumElementsBeetwenZero += *numbers[index];
}
}
if (checkZeroElements)
{
std::cout << "Sorry, array have less than two zero elements.";
}
else
{
std::cout << "Sum even index elements: " << sumEvenIndexElements << std::endl;
}
}
lengthOfArray
is a constant variable, it's value would not be chagned during runtime after initialization.
But it's value - userInput
is not a constant, it dependes on runtime user input. As pointed here
A constant value is an explicit number or character such as 1 or 0.5 or 'c'.
You should use std::vector instead of an array, as suggested in Paul Evans's answer, or assign a proper constant value to the lengthOfArray
, which will be known at the time of compilation, eg:
const int lengthOfArray = 10;
Your code:
std::cout << "Write array length:" << std::endl;
std::cin >> userInput;
const int lengthOfArray = userInput;
int numbers [lengthOfArray];
won't work as per the compiler error you're getting.
std::vector
plays a lot nicer:
std::cout << "Write array length:" << std::endl;
std::cin >> userInput;
const int lengthOfArray = userInput;
std::vector<int> numbers(lengthOfArray, 0);
will create a std::vector
of int
of length lengthOfArray
all initialised to 0
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.