arc_lupus
arc_lupus

Reputation: 4114

Creating dynamic arrays without "new" in VC++

I want to create an array in Visual Studio as it is possible in C99:

int function(int N)
{
    int x[N];
    return 1;
};

But even VS2013 doesn't support this. Is there another way (except using new and delete) to create x without the need to fix N at translation time? Thank you very much!

Upvotes: 1

Views: 197

Answers (3)

Alex Reinking
Alex Reinking

Reputation: 19916

The condoned way of doing this in C++ is by using vectors

#include <vector>

int function(int N)
{
    std::vector<int> x(N);
    return 1;
};

If you know that N won't be enormous (and since you seem to want this memory on the stack, anyway), you can use _alloca, which is a C function. See the documentation here.

#include <malloc.h>

int function(int N)
{
    int *x = _alloca(sizeof(int)*N);
    return 1;
};

This isn't really recommended, and has been superceded by _malloca, which requires a call to _freea after you're done with the memory.

Note that both versions will free the memory when the function exits, but the first version will allocate memory on the heap, whereas the second will allocate on the stack (and therefore has a much stricter upper limit on N). Besides the convenience and low-overhead of the std::vector class, using C-style pointers in a C++ program is kind of a downer anyway. :)

Upvotes: 2

azz
azz

Reputation: 5930

In order for an array in C++ to be defined on the stack (i.e. without new), the size of it must be known at compile time, such as a const int or a preprocessor macro. As this is not the case in this situation, you can use the following instead:

#include <vector>
using namespace std;
// ...
int function(int n)
{
    vector<int> x (n);
    return 1;
}

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

There is no such a possibily to define a variable length array in the stack in C++. But you can use std::vector instead though it allocates memory in the heap.

Upvotes: 0

Related Questions