0
int higher_element = arr[0];

for(int i = 0; i < length; i++)
    if(arr[i] > higher_element)
        higher_element = arr[i];

cout << "Higher element in an unsorted array :" << higher_element << endl;

int Hash[higher_element] = {0};

Here I want to create a new array of size higher_element and initialize it to 0 but array is not creating, only a garbage value is created.

The output of the higher element is 12.

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
  • 4
    Use `std::vector`. – Jarod42 Jul 20 '20 at 16:57
  • 1
    `int Hash[higher_element]={0};` in `c++` the size of this type of array must be a compile time constant. [https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – drescherjm Jul 20 '20 at 16:58
  • 1
    See operators `new []` and `delete[]`. – Thomas Matthews Jul 20 '20 at 16:58
  • Note the C++ compilers that I know of with support for variable length arrays do not zero-initialize the entire array when you `int Hash[higher_element]={0};`. The first element is zeroed, the rest are not. This is the price of using non-standard extensions. The behaviour's not standard. – user4581301 Jul 20 '20 at 17:24

2 Answers2

2

Since you are using C++, I suggest you to use vector. Here's the std::vector solution for your problem.

std::vector<int> Hash(higher_element);

Vectors initialize to 0 automatically. But for your clarification,

std::vector<int> Hash(higher_element,0);
Kavishka Gamage
  • 102
  • 2
  • 10
0

You can only use const in declaring the array.

If you want to use a variable to define the size of the array, try this

int *Hash;
Hash = new int[higher_element];

Hope to help you.

Kungfu Frog
  • 81
  • 1
  • 8
  • 1
    This is wrong because you failed to `delete []` it later. Better to use `std::make_unique(higher_element)` because that returns a smart pointer that will take care of deletion for you (even in cases of abnormal return like exceptions) – Ben Voigt Jul 20 '20 at 17:02
  • @Ben Voigt, I have described the basic use of the new operator. In that program, we have to use the delete operator to destroy the malloced array. – Kungfu Frog Jul 20 '20 at 17:07
  • Terminology warning: The above comment is misleading. Do not `delete` `malloc`ed storage. – user4581301 Jul 20 '20 at 17:29