-2

Suppose I have this piece of code:

#include <iostream>

int array[];

int main()
{
    int length;

    std::cin >> length;

    for (int i = 0; i < length; i++)
    {
        std::cin >> array[i];
    }
}

This does not work since I did not declare the size of the array at the start of the program. However, I am not able to declare the size of the array since the length of the array depends on user input and I only get this input after I declare the array. (I require this array to be a global variable so I cannot declare it after declaring the length variable)

  • 7
    Why not use `std::vector` instead? You can resize it to your will whenever you want. – Yksisarvinen Mar 17 '23 at 11:52
  • You seem to want a variable length array (VLA). But these are not supported in *standard* C++ (GNU C++ has them as an extension). As previous commentator said, used a `std::vector`. – Adrian Mole Mar 17 '23 at 11:55
  • The answer to the literal question in the title is: Yes: `extern int array[]; /*more code here */ int array[42];`. But I doubt that is what you were looking for. Use `std::vector` and `array.resize(length)`. – j6t Mar 17 '23 at 12:26
  • Not possible. The compiler needs to know the size of all variables. (`new` solves this problem *because it's not a variable*) – user253751 Mar 17 '23 at 12:40

3 Answers3

1

You need to declare pointer to make it dynamic so length is allocated at runtime.

#include <iostream>
int* array;
int main()
{
    int length;

    std::cin >> length;
    
    array = new int[length];
    
    for (int i = 0; i < length; i++)
    {
        std::cin >> array[i];
    }
}

after usage make sure to free memory by

delete[] array

Alternatively, you can use vector which will handle size and deletion automatically.

Opsi Daisy
  • 80
  • 1
  • 6
-1

If you really want to use array instead of some stl container you can use malloc and char*:

#include <iostream>

int* array;

int main()
{
    int length;

    std::cin >> length;
    array = (int*)malloc(length*sizeof(int))

    for (int i = 0; i < length; i++)
    {
        std::cin >> array[i];
    }
}

This is more C than C++ but it certainly works.

kiner_shah
  • 3,939
  • 7
  • 23
  • 37
Cryptolis
  • 84
  • 3
-1

You need to do dynamic allocation for this and then release the allocation

  • 1
    don't forget to `delete[]` the array when you are done using it: `delete[] array;`. Better to use `std::vector` though, as it handles these details internally for you. – Remy Lebeau Mar 17 '23 at 17:53