-2

I am struggling with C++. I learned Java before and i think it is much easier, tbh. Currently, I am trying to code a counting sort algorithm with c++. I want to get the maximum of my array to declare my helping array with the size = maximum +1; I tried several ways but nothing works. It always shows "variable cannot be used as a constant". I also have found a code which does the same as mine but seems like to work. Can anyone give me some hints or solutions?

Thanks in advance.

#include <iostream>
#include <array>
#include <algorithm>

using namespace std;


int getMax(int arr[], int size) 
{
    int max = arr[0];

    for (int i = 1; i < sizeof(arr); i++) {
        if (arr[i] > max) {
            max = arr[i];                                   
        }
    }

    return max;
}
void countingSort(int *arr, int size)
{
    int max = getMax(arr, size);
    int hilfsArr[max + 1];

}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
Traffix
  • 25
  • 6
  • 2
    For array of dynamic size, just use `std::vector` – Jarod42 Dec 12 '20 at 14:14
  • `int hilfsArr[max + 1];` is not legal in standard `c++`. Also `for (int i = 1; i < sizeof(arr); i++) {` is not going to work. `sizeof(arr)` will be the size of a pointer. Interestingly you have a `int size` parameter. – drescherjm Dec 12 '20 at 14:15
  • `getMax` is also broken, `sizeof(arr)` should be `size`. – Jarod42 Dec 12 '20 at 14:18
  • Moving to a second language is always hard, because you've developed habits that work in your first language but don't work in the second. Moving to a third language is much easier, because you saw the pitfalls when you made the earlier move., – Pete Becker Dec 12 '20 at 16:24

2 Answers2

2

For array of dynamic size, just use std::vector, something like:

void countingSort(int *arr, int size)
{
    std::vector<int> counter(*std::max_element(arr, arr + size));
    // ...
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
-1

You can not use variables for compile time array size simply because compiler has no way of knowing what the value returned by your getMax function will be ...

You need to use dynamic arrays in cases like this...

void countingSort(int *arr, int size)
    {
    int max = getMax(arr, size);
    int *hilfsArr=new int[max + 1]; // allocate

    ... here put the rest of your code for this function

    delete[] hilfsArr; // free before exiting function
    }
Spektre
  • 49,595
  • 11
  • 110
  • 380