Variable Length Arrays: How to create a buffer with variable size in C++

variable length array c++
variable length array in c
why are variable length arrays bad
variable size array c
c variable length array in struct
variable length array c++ vector
c variable length array initialization
c++14 variable length array

I am currently writing a moving average class.

The goal is to be able to specify the buffer size as part of the constructor when a new object of class Running_Average is created.

#include <iostream>
#include "Complex.h"
#include <cmath>
#include<stdio.h>
#include<stdlib.h>
#include <windows.h>

using namespace std;

class Running_Average
{
public:
    double sum = 0;
    double average = 0;
    int i;

    double Average(void); // Member functions declaration
    void AddSample(double);
    Running_Average(int);
};


Running_Average::Running_Average(int size) {
    int buffersize = size;
    double buffer[buffersize] = { 0 };
}

void Running_Average::AddSample(double val)  //Add new values to buffer
{
    for (i = 9; i>0; i--)
    {
        buffer[i] = buffer[i-1];
    }
    buffer[0] = val;
}

double Running_Average::Average(void) //Calculate Average of current values in buffer
{
    for (i = 0; i<buffersize; i++)
    {
        cout << buffer[i] << endl;
        sum += buffer[i];
    }
    average = sum / buffersize;
    sum = 0; 
    return average;
}

int main()
{
    double value;
    int i;
    int f = 0;
    Running_Average test;

    for (i = (40); i < (50); i++)
    {
        test.AddSample(i);
    }

    while (1) 
    {
        i = rand() % 100;
        test.AddSample(i);
        value = test.Average();
        cout << endl;
        cout << value << endl;
        cout << endl; 
        Sleep(1000);
    }

}

However, the constructor is giving me grief:

Running_Average::Running_Average(int size) {
    int buffersize = size;
    double buffer[buffersize] = { 0 };
}

Specifically:

buffer[buffersize]

throws an error in visual studio saying:

expression must have a constant size.

I want the user to specify what buffer size they want to work with when they create a new object by passing their value to the constructor.

How can I make this work without it throwing an error?

Thanks for your help!

EDIT: SOLVED! Thank you everyone for your assistance! I managed to get the function working by using the std::vector to define a variable sized array.

There are plenty of ways to do this. The ones that come to mind from best to worst are :

1 Use std::vector

int buffersize = size;
std::vector<double> buffer(buffersize);

2 Built-in unique pointer or shared pointer (depending on usage)

int buffersize = size;
auto buffer = make_unique<double[]>(buffersize) // C++14

int buffersize = size;
auto buffer = make_shared<double[]>(buffersize) // C++14

3 Allocate manually

int buffersize = size;
double *buffer = new double[buffersize];

// delete [] buffer, must be called later

4 Allocate on the stack (not advised, and platform dependent)

int buffersize = size;
double *buffer = alloca(buffersize * sizeof(*buffer));

Note that in all these cases you could index buffer just like an array.

Variable Length Arrays: How to create a buffer with variable size in , There are plenty of ways to do this. The ones that come to mind from best to worst are : 1 Use std::vector int buffersize = size; std::vector<double>  The size of variable length array in c programming must be of integer type and it cannot have an initializer. We know that two array types are compatible if: Both arrays must have compatible element types.

Standard C++ doesn't have variable length arrays. (Why?) The size of an array must be a constant expression. Some compilers have non-standard extensions that allow VLAs, but you shouldn't rely on them. Use std::vector when you need an array which can have a variable length and can be resized.

Variable Length (Using the GNU Compiler Collection (GCC)), Standard C++ doesn't have variable length arrays. (Why?) The size of an array must be a constant expression. Some compilers have non-standard extensions  Standard C++ doesn't have variable length arrays. The size of an array must be a constant expression. Some compilers have non-standard extensions that allow VLAs, but you shouldn't rely on them. Use std::vector when you need an array which can have a variable length and can be resized.

Variable Length Arrays, Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are The length of an array is computed once when the storage is allocated and is remembered for the scope of the array in case you access it with sizeof . If you want to pass the array​  This doesn't work. Variable sized structs must be created with malloc, which means no constructor. If you declare them as variables, the variable size part is set to zero. The space just isn't allocated. And initializing a member array from a heap pointer just doesn't make sense (or compile).

Based on the way you use buffer I would suggest using an std::list<double> for it.

Add this to the beginning of Running_Average:

class Running_Average
{
    private:
        list<double> buffer;

        const size_t MaxBufferSize;

    public:
        ...

The constructor :

Running_Average::Running_Average(size_t size)
:   MaxBufferSize(size)
{
}

AddSample() and Average() :

void Running_Average::AddSample(double val)
{
    if (buffer.size() == MaxBufferSize)
    {
        buffer.pop_back();
    }
    buffer.push_front(val);
}

double Running_Average::Average()
{
    double sum = 0;
    for (auto a : buffer)
    {
        cout << a << endl;
        sum += a;
    }
    return sum / buffer.size();
}

I would also remove the sum, average and i member variables and instead declare them where they are used (if needed).

Variable-length array, The C99 standard added a feature to dimension an array on-the-fly. One way to implement a VLA is to specify the array size as a variable, as is done in the following code: It's possible in C to create a variable length array. BUFSIZE should be equal to the size of your buffer in bytes. read() will stop reading when the buffer is full. Here is an example: #define MY_BUFFER_SIZE 1024 char mybuffer[MY_BUFFER_SIZE]; int nBytes = read(sck, mybuffer, MY_BUFFER_SIZE);

expression must have a constant size double buffer[buffersize] = { 0 };

First, buffersize isn't a constexpr. It is a variable that changes during runtime.

When specifying a size for an array, as per the standard definition of array:

The constant expression specifies the bound of (number of elements in) the array. If the value of the constant expression is N, the array has N elements numbered 0 to N-1,

Sample declaration of an array with 5 elements of type double should be like:

double buffer[5]; // 5 is a literal

constexpr int size = 5;
double buffer[size];    // size is constexpr

Second, buffer is a variable-length array (VLA). VLAs are partly supported in some compilers as an extension.

How can I make this work without it throwing an error?

If you need the length to be variable, use std::vector and initialize it in your constructor:

class Running_Average {
    Running_Average(int size): buffer(size, 0) {}
    std::vector<double> buffer;
}

The New C:Why Variable Length Arrays?, In computer programming, a variable-length array (VLA), also called variable-​sized, In C, the VLA is said to have a variably modified type that depends on a value (see The following C99 function allocates a variable-length array of a specified size, fills it with Not logged in; Talk · Contributions · Create account · Log in  Next, we’ll need a variable to store the buffer length. The buffer length is the current number of filled elements (elements we’ve written to). Each time we write a new value, we’ll increment the buffer length by 1. Each time we read a value, we’ll decrement the buffer length by 1.

How to make an array with variable size in the C language, Such arrays are called variable length arrays or VLAs for short. This means that you cannot declare an array whose size varies with the  Variable length arrays can have a size as required by the user i.e they can have a variable size. A program to implement variable length arrays in C++ is given as follows − Example

Variable Length Array In C Programming With Example, You can only do that in C99 variable-length arrays [code]void somefunc(int size) { int vla[size]; // do something with vla } // vla is automatically destroyed when out  If you know the maximum length of array, just initialize the array to that length and use an integer to tell the program how much of that array to use. If it's the difference between 7,10 bytes then you are not wasting that much memory allocation. improve this answer. answered May 29 '18 at 22:16. 4 silver badges.

Legitimate Use of Variable Length Arrays « null program, In this article, you will learn how to create Variable Length Array in C programming with explicit Until now, we have used an array that had constant size. I'm working on creating a queue to hold variable sized data buffers up to 256 bytes in length, however most often the buffers will be much smaller (typically around 10-15 bytes). To avoid the was

Comments
  • If you are not permitted to use the standard library and use the proper std::vector you will have to dynamically allocate a buffer using new. If you use new make sure your class follows the rule of 3.
  • check VLA and better use std::vector
  • @codekaizer Unfortunately, there seems to be a lack of good canonical questions for problems like these and they end up being closed as a duplicate of some bad debugging question. There are some questions asking why variable length arrays aren't standard C++, but I don't think they count as a duplicate.
  • updated title to be easily identified when there are future duplicate posts relating to this.
  • Possible duplicate of Variable Length Arrays in C++14?
  • @codekaizer It's kind of depracated, but it's a way of allocating memory on the stack dependent on runtime. People don't like it because it can kill some optimizations, or cause stack overflow. Good addition! Feel free to edit it (or I could).
  • Hey Gill Bates (love that name) I used your first suggestion with std::vector but for whatever reason Addsample and Average methods do not recognize the existanve of the "buffer" and "buffersize" entities in the constructor anymore whereas previously it seemed like the Addsample and Average methods had access to the entities in the constructor. Any idea what could be going wrong?
  • @AndrewSchroeder I doubt the other methods had access to the constructor variables before. The only way to make the variables in your constructor accessed by other methods is making them member/class variables. Along with double sum and doule average, you can add std::vector<double> buffer. Then you can write your constructor as: Running_Average::Running_Average(int size) : buffer(size) { } (initializer list). This should work. If you then want to access the size of the buffer, you can do buffer.size(), which is a built-in std::vector function