-1

I've been trying to give an array its size through a variable, but it's not working because "must have a constant value".

int processes[] = { 1, 2, 3 };
int n = sizeof processes / sizeof processes[0];
...
findavgTime(processes, n);

-------------------------------------------------

void findavgTime(int processes[], int n, int bt[])
{
    int wt[n], tat[n]; //These two vars are giving me the error
}

Am I missing something?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Elias Marrero
  • 187
  • 2
  • 15

2 Answers2

1

As you've seen, you can declare an array with a non-constant size like this. You could, however allocate it dynamically using new:

int* wt = new int[n];
int* tat = new int[n];

Just don't forget that you need to delete[] these arrays when you're done.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 4
    Almost no end user actually needs to use `new`. There is `std::vector` instead. – underscore_d Dec 12 '20 at 20:19
  • 1
    He wouldn't need to think about deleting, if he'd use a `std::unique_ptr`. But anyhow, like said the standard library has vector for dynamic arrays. – JHBonarius Dec 13 '20 at 07:34
-1

You can allocate it on the heap like how Mureinik said, but you can also allocate it on the stack (as you were trying to do) with alloca() like this:

int* wt = (int*)alloca(n * sizeof(int));
int* tat = (int*)alloca(n * sizeof(int));

free() should not be called as it is allocated on the stack, not the heap.

Some say using alloca() is bad practice because if the call causes a stack overflow, program behavior is undefined. This shouldn't be a problem as long as the array isn't too long.

Colbsters
  • 54
  • 2
  • You can do this **if** your compiler supports `alloca`. It is not part os standard C++. – Pete Becker Dec 13 '20 at 02:36
  • Sure, but **most** (if not all) mainstream compilers support it, I tested nearly all the compilers on Compiler Explorer and it was supported. (MSVC didn't work but I know it supports it.) – Colbsters Dec 13 '20 at 03:27