How do i set an array to have custom lenght?

0

I am getting an error when i run this code. The error code is 0xC00000FD and I can't seem to find a fix for what i need. Can someone please help me? Here's the code:

#include<iostream>
#include<conio.h>

using namespace std;

int main()
{
    int n;
    int arr[n];
    int i;
    int sum=0, avg=0;

    cout<<"array lengh: ";

    cin>>n;
    cout<<"Enter "<<n<<" array elements: ";
    for(i=0; i<n; i++)
    {
        cin>>arr[i];
        sum = sum + arr[i];
    }
    cout<<"\nThe array elements are: \n";
    for(i=0; i<n; i++)
    {
        cout<<arr[i]<<"  ";
    }
    cout<<"\n\nSum of all elements is: "<<sum;
    avg = sum/10;
    cout<<"\nAnd average is: "<<avg;
    getch();

    return 0;
}

c++
arrays

2 Answers

2

There are two major problems in your code. First, C++ does not have "variable length arrays" (VLAs), although some compilers support them as an extension.

More importantly, even if your compiler does support them, you are attempting to define the size of your arr before you have read the value of n.

To fix these issue you should: (a) use the std::vector container, rather than a plain array; and (b) only declare that after you have read in the value of n.

Here's a 'quick fix':

#include <iostream>
#include <conio.h>
#include <vector> // For the "std::vector" definition

using namespace std;

int main()
{
    int n;
//    int arr[n]; // Here, the value of "n" is undefined!
    int i;
    int sum=0, avg=0;

    cout<<"array lengh: ";

    cin>>n;
    std::vector<int> arr(n); // This can now be used 'almost' like a plain array
    cout<<"Enter "<<n<<" array elements: ";
    for(i=0; i<n; i++)
    {
        cin>>arr[i];
        sum = sum + arr[i];
    }
    cout<<"\nThe array elements are: \n";
    for(i=0; i<n; i++)
    {
        cout<<arr[i]<<"  ";
    }
    cout<<"\n\nSum of all elements is: "<<sum;
    avg = sum/10;
    cout<<"\nAnd average is: "<<avg;
    getch();

    return 0;
}
answered on Stack Overflow Dec 14, 2020 by Adrian Mole • edited Dec 14, 2020 by Adrian Mole
0

Standard C++ does not support variable length arrays. std::vector can accomplish what you want. It is also possible to allocate memory of the desired size with new int[size] and use a pointer to reference the data rather than an array. However, this doesn't have any bounds checking, so there is the possibility of memory corruption. And the allocated memory must be explicitly freed with delete[]. So std::vector is my preferred solution.

answered on Stack Overflow Dec 14, 2020 by Jeff Spencer

User contributions licensed under CC BY-SA 3.0