0
#define N 10
int (*p)[N] = new int[N];

// or

typedef int TenInts[N];
TenInts *p = new TenInts;

Is this something the C++ language simply disallows? Are there any workarounds? (except std::vector as all I need is a dynamically allocated array with known compile-time size)\

I need new as I'm putting the static array inside a template that uses new, and the template accepts a generic type T. Consider, template<typename T> void f() {T *t = new T;}, where I want T to be a static array.

11
  • 4
    What's the question? Commented Feb 16, 2017 at 20:44
  • C++ arrays are just pointers to the first index Commented Feb 16, 2017 at 20:45
  • @m_callens I think no, if C++ is compatible enough with C.. and I think I know enough about C.. Commented Feb 16, 2017 at 20:46
  • @KerrekSB Are there any workarounds? As I wrote there.. Commented Feb 16, 2017 at 20:46
  • @MinjaeKim, no, in general C++ is not compatible with C, but the very opposite is true. Commented Feb 16, 2017 at 20:47

5 Answers 5

1

you want

int *p = new int[N];

you cannot specify at compile time a size for an array that you intend to dynamically allocate. Why would you do that anyway

Sign up to request clarification or add additional context in comments.

1 Comment

dealing with templates.. trying to make them accept a static array.. std::array from the other answer seems to help.
1

as all I need is a dynamically allocated array with known compile-time size

You don't need to use new in that case.

Just use

#define N 10
std::array<int,N> p;

4 Comments

I need new as I'm putting the static array inside a template that uses new. Anyway your std::array helps.
I'll accept your answer if you edit your answer to use new.
I don't get why new is necessary (since N is known at compile time) can you elaborate about that requirement please?
The template takes a generic type T. Everything seems to be okay if T is std::array<...>. Please edit your answer as your answer did help.
1

You cannot use

int (*p)[N] = new int[N];

However, you can use:

int (*p)[N] = new int[1][N];

Comments

0

You can write:

int (*p)[N] = new int[1][N];

or replace 1 by larger numbers if you want several rows.

1 Comment

You have been ninja'd by R Sahu.
0

Perhaps this is what you want.

#include <array>
constexpr size_t N = 10;
auto * ptr = new std::array<int, N>();

This allows you to create an array with compile-time constant size at runtime using new.

Edit: I'm assuming that, when you say "my template uses new", you mean new as opposed to new[]. This implies that your template eventually calls delete as opposed to delete[].

2 Comments

Hmm, that's knd of weird IMO.
@πάνταῥεῖ I agree

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.